Array - 53. Maximum Subarray

时间:2022-07-25
本文章向大家介绍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;
    }
}