美文网首页
Leetcode动态规划-53. Maximum Subarra

Leetcode动态规划-53. Maximum Subarra

作者: ultimateYu | 来源:发表于2020-08-12 15:55 被阅读0次

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

    相关文章

      网友评论

          本文标题:Leetcode动态规划-53. Maximum Subarra

          本文链接:https://www.haomeiwen.com/subject/ohcmdktx.html