文章 224
评论 6
浏览 200762
Array - 53. Maximum Subarray

Array - 53. Maximum Subarray

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:

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;
    }
}

标题:Array - 53. Maximum Subarray
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/24/1561386957656.html

Nothing just happens, it's all part of a plan.

取消