LeetCode53 Maximum sum of subarray
classic dp:
dp[i] represents the maximum sum of subarray which ends in nums[i],
and dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]). and since we have to include nums[i] due to it’s on the defination of dp[i], and when dp[i-1]<0 we can just choose not to add it. so the equation can be modified as:
dp[i] = nums[i] + dp[i-1] < 0 ? 0: dp[i-1];
and clearly, we need a global variable to keep record of the global maximum.
so the code will be:
class Solution {
public int maxSubArray(int[] nums) {
if(nums==null || nums.length == 0) return 0;
int[] dp = new int[nums.length];
dp[0] = nums[0];
int res = dp[0];
for(int i = 1; i<nums.length;i++){
dp[i] = nums[i] + (dp[i-1]<0 ? 0: dp[i-1]);
res = Math.max(dp[i], res);
}
return res;
}
}

浙公网安备 33010602011771号