Skip to content

Commit 9e391e4

Browse files
authored
Update maximum-subarray.cpp
1 parent 016923a commit 9e391e4

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

C++/maximum-subarray.cpp

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,11 @@
44
class Solution {
55
public:
66
int maxSubArray(vector<int>& nums) {
7-
const auto& max_num = *max_element(nums.cbegin(), nums.cend());
8-
if (max_num < 0) {
9-
return max_num;
10-
}
11-
int global_max = 0, local_max = 0;
7+
int result = numeric_limits<int>::min(), curr = numeric_limits<int>::min();
128
for (const auto &x : nums) {
13-
local_max = std::max(0, local_max + x);
14-
global_max = std::max(global_max, local_max);
9+
curr = (curr == numeric_limits<int>::min()) ? x : max(curr + x, x);
10+
result = max(result, curr);
1511
}
16-
return global_max;
12+
return result;
1713
}
1814
};

0 commit comments

Comments
 (0)