[LeetCode]Maximum Subarray

Posted skycore

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]Maximum Subarray相关的知识,希望对你有一定的参考价值。

题目描述:

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

解题思路:

 

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int max_sum = INT_MIN;
 5         int sum = 0;
 6         for (int i = 0; i < nums.size(); ++i) {
 7             sum += nums[i];
 8             if (sum > max_sum) {
 9                 max_sum = sum;
10             } 
11             
12             if (sum <= 0) {
13                 sum = 0;
14             }
15         }
16         
17         return max_sum;
18     }
19 };

 

以上是关于[LeetCode]Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Degree of an Array

[Leetcode] Maximum Subarray

[LeetCode]Maximum Subarray

#Leetcode# 53. Maximum Subarray

LeetCode 53. Maximum Subarray

[leetcode]Array-697. Degree of an Array