-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum_subarray.cpp
57 lines (52 loc) · 1.32 KB
/
maximum_subarray.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* =====================================================================================
*
* Filename: maximum_subarray.cpp
*
* Description: 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.
*
* Version: 1.0
* Created: 09/04/18 08:07:50
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <vector>
class Solution {
public:
int maxSubArray(const std::vector<int>& nums) {
int max_sum = INT_MIN;
int last_sum = 0;
for (const int val : nums) {
last_sum += val;
if (max_sum < last_sum) {
max_sum = last_sum;
}
if (last_sum < 0) {
last_sum = 0;
}
}
return max_sum;
}
};
int main(int argc, char* argv[]) {
std::vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
if (argc > 3) {
nums.clear();
for (int i = 1; i < argc; i++) {
nums.push_back(atoi(argv[i]));
}
}
int max = Solution().maxSubArray(nums);
printf("%d\n", max);
return 0;
}