File tree Expand file tree Collapse file tree 1 file changed +34
-7
lines changed Expand file tree Collapse file tree 1 file changed +34
-7
lines changed Original file line number Diff line number Diff line change 1+ // [참고]
2+ // 카데인 알고리즘: 이전요소의 부분합을 알면 현재요소의 최대값을 알 수 있다.
3+ // 양수만이라면 단순히 dp로 dp[nums.length-1] 값이나 total이라는 계산값을 리턴하겠지만,
4+ // 음수가 포함되었으므로 bestSum과 currentSum을 별개의 변수로 처리한다.
5+ // currentSum은 최대 sum을 구해야 하므로 음수값일때 강제로 0으로 업데이트 후 계산을 실행한다.
6+ // https://velog.io/@wind1992/Leetcode-53.-Maximum-Subarray
7+ //
8+ // [풀이방식]
9+ // 1. 카데인 알고리즘 2. DP
10+ // [성능]
11+ // dp 배열보다 변수를 사용하는 것이 공간 복잡도를 줄일 수 있다. 또한 for문 1개로 해결 가능하다.
112class Solution {
213 public int maxSubArray (int [] nums ) {
3- int res = nums [0 ];
4- int total = 0 ;
14+ int bestSum = nums [0 ];
15+ int currentSum = 0 ;
516
617 for (int n : nums ) {
7- if (total < 0 ) {
8- total = 0 ;
18+ if (currentSum < 0 ) { // 1. 업데이트
19+ currentSum = 0 ;
920 }
10- total += n ;
11- res = Math .max (total , res );
1221
22+ // 2. 계산
23+ currentSum += n ;
24+ bestSum = Math .max (currentSum , bestSum );
1325 }
14- return res ;
26+ return bestSum ;
27+ }
28+
29+ public int maxSubArrayDp (int [] nums ) {
30+ int n = nums .length ;
31+ int [] dp = new int [n ];
32+
33+ dp [0 ] = nums [0 ];
34+ int maxSum = dp [0 ];
35+
36+ for (int i = 1 ; i < n ; i ++) {
37+ dp [i ] = Math .max (nums [i ], dp [i - 1 ] + nums [i ]);
38+ maxSum = Math .max (maxSum , dp [i ]);
39+ }
40+
41+ return maxSum ;
1542 }
1643}
You can’t perform that action at this time.
0 commit comments