Skip to content

Commit 1bc95ef

Browse files
committed
문제 추가
1 parent 33ff1f8 commit 1bc95ef

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

maximum-subarray/jdalma.kt

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
import kotlin.math.max
6+
7+
class `maximum-subarray` {
8+
9+
fun maxSubArray(nums: IntArray): Int {
10+
return usingDP(nums)
11+
}
12+
13+
/**
14+
* TC: O(n), SC: O(n)
15+
*/
16+
private fun usingDP(nums: IntArray): Int {
17+
val dp = IntArray(nums.size).apply {
18+
this[0] = nums[0]
19+
}
20+
21+
for (index in 1 until nums.size) {
22+
dp[index] = max(nums[index], nums[index] + dp[index - 1])
23+
}
24+
25+
return dp.max()
26+
}
27+
28+
/**
29+
* TC: O(n), SC: O(1)
30+
*/
31+
private fun usingKadane(nums: IntArray): Int {
32+
var (current, max) = nums[0] to nums[0]
33+
34+
for (index in 1 until nums.size) {
35+
current = max(nums[index], current + nums[index])
36+
max = max(max, current)
37+
}
38+
39+
return max
40+
}
41+
42+
@Test
43+
fun `정수 배열의 하위 배열 중 가장 큰 합을 반환한다`() {
44+
maxSubArray(intArrayOf(-2,1,-3,4,-1,2,1,-5,4)) shouldBe 6
45+
maxSubArray(intArrayOf(1)) shouldBe 1
46+
maxSubArray(intArrayOf(5,4,-1,7,8)) shouldBe 23
47+
}
48+
}

0 commit comments

Comments
 (0)