编程语言:JAVA
题目描述:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解题思路:
这道题题目非常简单,但是做起来就没那么简单了。博主首先想到的也是唯一想到的方法就是暴力穷举法,时间复杂度很高O(3),果不其然,提交的时候超时。
Kadane Algorithm主要思想是,假设,数组中前i-1项的和为sum[i-1],对于第i个数字,则由公式
这个公式的直观解释为:当前i-1个数组的和加上arr[i]还没有arr[i]大的时候,就不考虑前i-1个数字,从当前数字开始新的计算。
保留一个max保存最大的值,每次都和max比较。
代码:
class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE, curSum = 0;
for (int num : nums) {
curSum = Math.max(curSum + num, num);
res = Math.max(res, curSum);
}
return res;
}
}
解法二:
这道题题目中的提示是要按照分制法来求解的,显然之前的算法不太符合题目本意。