1. 程式人生 > >【LeetCode】120.Maximum Subarray

【LeetCode】120.Maximum Subarray

題目描述(Easy)

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

題目連結

https://leetcode.com/problems/maximum-subarray/description/

Example 1:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

演算法分析

【劍指】42.連續子陣列的最大和

提交程式碼:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int maxSum = INT_MIN, sum = 0;
        
        for (int i = 0; i < nums.size(); ++i) {
            sum = max(nums[i] + sum, nums[i]);
            maxSum = max(maxSum, sum);
        }
        
        return maxSum;
    }
};