Leetcode动态规划-53. Maximum Subarra

2020-08-12  本文已影响0人  ultimateYu

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.

Solution:

方法一:动态规划

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int max_result = nums[0];   
        int max_pre = 0;
        for(const auto& x : nums){
            max_pre = max(max_pre + x, x);
            max_result = max(max_result, max_pre);
            
        }
        return max_result;
        
    }
};
上一篇下一篇

猜你喜欢

热点阅读