-
-
Notifications
You must be signed in to change notification settings - Fork 340
Expand file tree
/
Copy pathcrumbs22.cpp
More file actions
38 lines (32 loc) ยท 632 Bytes
/
crumbs22.cpp
File metadata and controls
38 lines (32 loc) ยท 632 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
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
/*
TC: O(n)
SC: O(1)
ํ์ด ๋ฐฉ๋ฒ:
- sum์ ํ์ฌ ๊ฐ์ ๋ํด๊ฐ๋ฉด์ ์ต๋๊ฐ์ ๊ฐฑ์ ํ๋ค
- ๋์ ํฉ์ด ์์๊ฐ ๋์ ๋ 0์ผ๋ก ๋ฆฌ์
ํ๋ค
๊ณ ๋ฏผํ๋ ์ผ์ด์ค(left์ right ํฌ์ธํฐ๋ฅผ ๋๊ณ ํ์์ ๋):
[-2, -1]
[-1, -2]
[-2, 1]
[-1, 1, 2, 1]
*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max = nums[0];
int sum = 0;
for (int i = 0; i < nums.size(); i++)
{
sum += nums[i];
if (sum > max)
max = sum;
if (sum < 0)
sum = 0;
}
return (max);
}
};