题目链接:https://www.nowcoder.com/practice/459bd355da1549fa8a49e350bf3df484
题目描述
输入一个长度为n的整型数组array,数组中的一个或连续多个整数组成一个子数组,子数组最小长度为1。求所有子数组的和的最大值。
数据范围:
1<=n<=2×10^5
-100 <= a[i] <= 100
要求:时间复杂度为 O(n),空间复杂度为 O(n)
进阶:时间复杂度为 O(n),空间复杂度为 O(1)
示例 1:
输入:[1,-2,3,10,-4,7,2,-5]
返回值:18
说明:经分析可知,输入数组的子数组[3,10,-4,7,2]可以求得最大和为18
示例 2:
输入:[2]
返回值:2
示例 3:
输入:[-10]
返回值:-10
解题代码
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
int res = array[0];
for (int i = 1; i < array.length; i++) {
array[i] += Math.max(0, array[i - 1]);
res = Math.max(res, array[i]);
}
return res;
}
}

评论区 0