-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path53-maximum-subarray.cpp
More file actions
29 lines (24 loc) · 864 Bytes
/
53-maximum-subarray.cpp
File metadata and controls
29 lines (24 loc) · 864 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Title: Maximum Subarray
// Description:
// Given an integer array nums,
// find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
// Link: https://leetcode.com/problems/maximum-subarray/
// Time complexity: O(n)
// Space complexity: O(1)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int partialSum = 0;
int largestSum = INT_MIN;
// greedy strategy
for (int num: nums) {
// add the value to the subarray
partialSum += num;
// update the max value
largestSum = std::max(partialSum, largestSum);
// discard the subarray if the sum is already negative
if (partialSum < 0) partialSum = 0;
}
return largestSum;
}
};