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;
    }
}
posted @ 2020-05-16 06:10  EvanMeetTheWorld  阅读(11)  评论(0)    收藏  举报