剑指offer:连续子数组的最大和(简单dp)
连续子数组的最大和
https://www.nowcoder.com/practice/459bd355da1549fa8a49e350bf3df484?tpId=13&tqId=11183&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey
题意:输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为 O(n).
思路:没啥好说的,简单dp
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
int res=array[0];
int maxx=array[0];
for(int i=1;i<array.length;i++){
maxx=Math.max(maxx+array[i],array[i]);
res=Math.max(maxx,res);
}
return res;
}
}
查看4道真题和解析