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
43 lines (37 loc) ยท 1.42 KB

File metadata and controls

43 lines (37 loc) ยท 1.42 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
39
40
41
42
43
// [์ฐธ๊ณ ]
// ์นด๋ฐ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜: ์ด์ „์š”์†Œ์˜ ๋ถ€๋ถ„ํ•ฉ์„ ์•Œ๋ฉด ํ˜„์žฌ์š”์†Œ์˜ ์ตœ๋Œ€๊ฐ’์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.
// ์–‘์ˆ˜๋งŒ์ด๋ผ๋ฉด ๋‹จ์ˆœํžˆ dp๋กœ dp[nums.length-1] ๊ฐ’์ด๋‚˜ total์ด๋ผ๋Š” ๊ณ„์‚ฐ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๊ฒ ์ง€๋งŒ,
// ์Œ์ˆ˜๊ฐ€ ํฌํ•จ๋˜์—ˆ์œผ๋ฏ€๋กœ bestSum๊ณผ currentSum์„ ๋ณ„๊ฐœ์˜ ๋ณ€์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.
// currentSum์€ ์ตœ๋Œ€ sum์„ ๊ตฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์Œ์ˆ˜๊ฐ’์ผ๋•Œ ๊ฐ•์ œ๋กœ 0์œผ๋กœ ์—…๋ฐ์ดํŠธ ํ›„ ๊ณ„์‚ฐ์„ ์‹คํ–‰ํ•œ๋‹ค.
// https://velog.io/@wind1992/Leetcode-53.-Maximum-Subarray
//
// [ํ’€์ด๋ฐฉ์‹]
// 1. ์นด๋ฐ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ 2. DP
// [์„ฑ๋Šฅ]
// dp ๋ฐฐ์—ด๋ณด๋‹ค ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๊ณต๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. ๋˜ํ•œ for๋ฌธ 1๊ฐœ๋กœ ํ•ด๊ฒฐ ๊ฐ€๋Šฅํ•˜๋‹ค.
class Solution {
public int maxSubArray(int[] nums) {
int bestSum = nums[0];
int currentSum = 0;
for (int n : nums) {
if (currentSum < 0) { // 1. ์—…๋ฐ์ดํŠธ
currentSum = 0;
}
// 2. ๊ณ„์‚ฐ
currentSum += n;
bestSum = Math.max(currentSum, bestSum);
}
return bestSum;
}
public int maxSubArrayDp(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
int maxSum = dp[0];
for (int i = 1; i < n; i++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
maxSum = Math.max(maxSum, dp[i]);
}
return maxSum;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.