LeetCode 53 Maximum Subarray (dp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/89601496

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.

题目链接:https://leetcode.com/problems/maximum-subarray/

题目分析:累加和为负则从0开始

1ms,时间击败99%

class Solution {
    public int maxSubArray(int[] nums) {
        int ans = Integer.MIN_VALUE, cur = 0;
        for (int i = 0; i < nums.length; i++) {
            cur += nums[i];
            ans = Math.max(ans, cur);
            if (cur < 0) {
                cur = 0;
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/89601496