leetcode-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.

給定一個整數數組 nums ,找到一個具有最大和的連續子數組(子數組最少包含一個元素),返回其最大和。

示例:

輸入: [-2,1,-3,4,-1,2,1,-5,4],
輸出: 6
解釋: 連續子數組 [4,-1,2,1] 的和最大,爲 6。
進階:

如果你已經實現複雜度爲 O(n) 的解法,嘗試使用更爲精妙的分治法求解。

O(n)=>

#include<iostream> 
#include<vector>
using namespace std;
// written by lrc123

class Solution
{
  public:
    int maxSubArray(vector<int> &nums)
    {
        if (nums.size() == 0)
            return 0;
        int ans = nums[0], temp = nums[0];
        for (int i = 1; i < nums.size(); i++)
        {
            if (temp > 0)
            {
                temp += nums[i];
            }
            else
            {
                temp = nums[i];
            }
            ans = max(temp, ans);
        }
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章