[LeetCode 53] Maximum Subarray
题目
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
测试案例
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
思路
最大子串和是一个动态规划问题。记,a[i - 1] 为 0 ~ i - 1 子串中最大子串和,sum[i - 1] 为以第 i - 1 个元素结尾的子串和的最大值。那么有如下递归式:
\[ \begin{align} sum[i] &= nums[i] + (sum[i - 1] > 0 \;?\; sum[i - 1] : 0) \\ a[i] &= max(a[i - 1],sum[i]) \end{align} \]
代码如下
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length, max = nums[0], sum = nums[0], temp;
for(int i = 1; i < n; i++){
temp = nums[i] + (sum > 0 ? sum : 0);
sum = temp;
if(max < temp){
max = temp;
}
}
return max;
}
}