Maximum Subarray

题目地址:
https://leetcode.com/problems/maximum-subarray/#/description

题目:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

解题思路:
这道题就是直接用dynamic programming来解。

代码:

public int maxSubArray(int[] nums) {
    int len = nums.length;
    int[] dp = new int[len];
    dp[0] = nums[0];
    int max = nums[0];
    for(int i = 1; i <= len - 1; i++){
        dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
        max = Math.max(max, dp[i]);
    }
    return max;
}





Comments

Popular Posts