forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdalma.kt
48 lines (38 loc) Β· 1.11 KB
/
jdalma.kt
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
44
45
46
47
48
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import kotlin.math.max
class `maximum-subarray` {
fun maxSubArray(nums: IntArray): Int {
return usingDP(nums)
}
/**
* TC: O(n), SC: O(n)
*/
private fun usingDP(nums: IntArray): Int {
val dp = IntArray(nums.size).apply {
this[0] = nums[0]
}
for (index in 1 until nums.size) {
dp[index] = max(nums[index], nums[index] + dp[index - 1])
}
return dp.max()
}
/**
* TC: O(n), SC: O(1)
*/
private fun usingKadane(nums: IntArray): Int {
var (current, max) = nums[0] to nums[0]
for (index in 1 until nums.size) {
current = max(nums[index], current + nums[index])
max = max(max, current)
}
return max
}
@Test
fun `μ μ λ°°μ΄μ νμ λ°°μ΄ μ€ κ°μ₯ ν° ν©μ λ°ννλ€`() {
maxSubArray(intArrayOf(-2,1,-3,4,-1,2,1,-5,4)) shouldBe 6
maxSubArray(intArrayOf(1)) shouldBe 1
maxSubArray(intArrayOf(5,4,-1,7,8)) shouldBe 23
}
}