Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

ย 

History

History
History
38 lines (33 loc) ยท 1.03 KB

File metadata and controls

38 lines (33 loc) ยท 1.03 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
time complexity: O(n)
space complexity: O(1)
์™ผ์ชฝ์—์„œ๋ถ€ํ„ฐ ๋ˆ„์ ํ•ฉ์„ ๊ตฌํ•˜๋˜, ๋”ํ•œ ๊ฐ’์ด ์Œ์ˆ˜๊ฐ€ ๋˜๋Š” ์ˆœ๊ฐ„ ์ง€๊ธˆ๊นŒ์ง€ ๋”ํ•œ ๊ฐ’์„ ๋ฒ„๋ฆฐ๋‹ค. (์ฆ‰, ์ง€๊ธˆ๊นŒ์ง€์˜ ์›์†Œ๋Š” ๋ชจ๋‘ subarray์—์„œ ์ œ์™ธํ•œ๋‹ค.) ์ด๋ ‡๊ฒŒ ๋ˆ„์ ํ•ฉ์„ ๊ณ„์‚ฐํ•˜๋ฉด์„œ, ๋ˆ„์ ํ•ฉ์˜ ์ตœ๋Œ€๊ฐ’์„ ์ฐพ์œผ๋ฉด ๋‹ต์ด ๋œ๋‹ค.
๋‹จ, ๋ชจ๋“  ์›์†Œ๊ฐ€ ์Œ์ˆ˜์ธ ๊ฒฝ์šฐ๋Š” ์˜ˆ์™ธ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•ด์ค€๋‹ค.
*/
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int ans = -10001;
int max = -10001;
int sum = 0;
for (int i = 0; i < n; i++) {
if (sum + nums[i] < 0) {
sum = 0;
} else {
sum += nums[i];
}
if (sum > ans) {
ans = sum;
}
if (max < nums[i]) {
max = nums[i];
}
}
// ๋ชจ๋‘ ์Œ์ˆ˜์ธ ๊ฒฝ์šฐ์˜ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ
if (max < 0) {
return max;
} else {
return ans;
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.