forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdalma.kt
More file actions
56 lines (48 loc) Β· 2.14 KB
/
jdalma.kt
File metadata and controls
56 lines (48 loc) Β· 2.14 KB
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
49
50
51
52
53
54
55
56
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import kotlin.math.max
import kotlin.math.min
class `maximum-product-subarray` {
fun maxProduct(nums: IntArray): Int {
return usingOptimizedDP(nums)
}
/**
* νμ¬μ κ°, μ΄μ μμΉμ μ΅λ λμ κ³±, μ΄μ μμΉμ μ΅μ λμ κ³± μ΄ μΈ κ°λ₯Ό λΉκ΅νμ¬ ν λ²μ μνλ‘ μ΅λ κ°μ λ°ννλ€.
* μμμ μμκ° κ³±ν΄μ Έ μ΅λ κ°μ΄ λμΆλ μ μκΈ°μ DP λ°°μ΄μ λ κ° μμ±νλ€.
* TC: O(n), SC: O(n)
*/
private fun usingDP(nums: IntArray): Int {
val (min, max) = IntArray(nums.size) { 11 }.apply { this[0] = nums[0] } to IntArray(nums.size) { -11 }.apply { this[0] = nums[0] }
var result = nums[0]
for (index in 1 until nums.size) {
max[index] = max(max(nums[index], nums[index] * max[index - 1]), nums[index] * min[index - 1])
min[index] = min(min(nums[index], nums[index] * max[index - 1]), nums[index] * min[index - 1])
result = max(max(min[index], max[index]), result)
}
return result
}
/**
* DP λ°°μ΄μ΄ μ
λ ₯λ°λ μ μμ λ°°μ΄λ§νΌ μμ±ν νμκ° μκ³ , μ΄μ κ°κ³Ό νμ¬ κ°λ§ κΈ°μ΅νλ©΄ λλ―λ‘ κ³΅κ°λ³΅μ‘λκ° κ°μ λμλ€.
* TC: O(n), SC: O(1)
*/
private fun usingOptimizedDP(nums: IntArray): Int {
var (min, max) = nums[0] to nums[0]
var result = nums[0]
for (index in 1 until nums.size) {
val (tmpMin, tmpMax) = min to max
max = max(max(nums[index], nums[index] * tmpMax), nums[index] * tmpMin)
min = min(min(nums[index], nums[index] * tmpMax), nums[index] * tmpMin)
result = max(max(min, max), result)
}
return result
}
@Test
fun `μ
λ ₯λ°μ μ μ λ°°μ΄μ κ°μ₯ ν° κ³±μ λ°ννλ€`() {
maxProduct(intArrayOf(2,3,-2,4)) shouldBe 6
maxProduct(intArrayOf(-2,0,-1)) shouldBe 0
maxProduct(intArrayOf(-10)) shouldBe -10
maxProduct(intArrayOf(-2,3,-4)) shouldBe 24
maxProduct(intArrayOf(-4,-3,-2)) shouldBe 12
}
}