53. Maximum Subarray

题目分析

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.

代码一

动态规划的思想,时间复杂度为 O(n),空间复杂度为 O(n)

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

代码二

时间复杂度 O(n),空间复杂度 O(1)

class Solution {
    public int maxSubArray(int[] nums) {
        int res = nums[0];
        int sum = nums[0];
        // 这种解法也是 dp 的解法,dp[i] 只跟 dp[i - 1] 有关,所以直接用 res 记录当前的最大值,再就是记住 dp[i - 1] 即可,sum 就起到记住 dp[i - 1] 的作用
        for(int i = 1; i < nums.length; i++) {
            sum = Math.max(nums[i], sum + nums[i]);
            res = Math.max(res, sum);
        }
        return res;
    }
}

你可能感兴趣的:(53. Maximum Subarray)