Array - 53. Maximum Subarray

2020-09-23 17:09:58 浏览数 (1)

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.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

思路:

找出数组中最大字串和,使用动态规划求解,转移方程是:f[i] = f[i-1] > 0 ? nums[i] f[i-1] : nums[i]

代码:

java:

代码语言:javascript复制
class Solution {

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

0 人点赞