目录结构
1.题目
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
public class Offer42 {
@Test
public void test() {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(nums));
}
public int maxSubArray(int[] nums) {
int max = Integer.MIN_VALUE, sum = 0;
for (int num : nums) {
sum += num;
max = Math.max(max, sum);
if (sum < 0) {
sum = 0;
}
}
return max;
}
}
- 时间复杂度:
- 空间复杂度: