描述
输入一个长度为n的整型数组array,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
数据范围:
1 <= n <= 10^51<=n<=10
5
-100 <= a[i] <= 100−100<=a[i]<=100
要求:时间复杂度为 O(n)O(n),空间复杂度为 O(n)O(n)
进阶:时间复杂度为 O(n)O(n),空间复杂度为 O(1)O(1)
public class ContinueArraySum {
public static void main(String[] args) {
ContinueArraySum continueArraySum = new ContinueArraySum();
int[] arr = {1,-2,3,10,-4,7,2,-5};
int result = continueArraySum.FindGreatestSumOfSubArray(arr);
System.out.println(result);
}
public int FindGreatestSumOfSubArray(int[] array) {
if(null == array || array.length == 0){
return 0;
}
int currenSum = 0; // 记录当前的和
int maxSum = 0x80000000;
for (int i = 0; i < array.length; i++) {
if(currenSum<=0){
// 如果小于等于0,那么再加上array[i]的和也是小于等于array[i],所以重新更新currenSum
currenSum = array[i];
}else{
currenSum += array[i];
}
if(currenSum > maxSum){
maxSum = currenSum;
}
}
return maxSum;
}
}