Problem 53

Maximum Subarray

Posted by Ruizhi Ma on July 26, 2019

问题描述

https://leetcode.com/problems/maximum-subarray/

解决思路

动态规划问题初挖,所谓动态规划,就是把一个大问题,分为无数个小问题,而且这些个小问题,可能还包含在其他小问题之内。

代码

class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        dp[0] = nums[0];
        int max = dp[0];
        
        for(int i = 1; i < n; i++){
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            max = Math.max(max, dp[i]);
        } 
        return max; 
    }
}