Skip to content

Commit 323259b

Browse files
authored
Create 1856-maximum-subarray-min-product.kt
1 parent 6698b8a commit 323259b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
fun maxSumMinProduct(nums: IntArray): Int {
3+
val prefix = LongArray(nums.size + 1)
4+
val stack = ArrayDeque<Pair<Int, Long>>()
5+
val mod = 1000000007L
6+
7+
for (i in nums.indices) {
8+
prefix[i + 1] = prefix[i] + nums[i]
9+
}
10+
11+
var res = 0L
12+
for ((i, n) in nums.withIndex()) {
13+
var start = i
14+
15+
while (stack.isNotEmpty() && stack.peekLast().second > n) {
16+
val (lastStart, value) = stack.removeLast()
17+
val total = prefix[i] - prefix[lastStart]
18+
res = maxOf(res, total * value)
19+
start = lastStart
20+
}
21+
22+
stack.addLast(start to n.toLong())
23+
}
24+
25+
for ((start, value) in stack) {
26+
val total = prefix[nums.size] - prefix[start]
27+
res = maxOf(res, total * value)
28+
}
29+
30+
31+
return (res % mod).toInt()
32+
}
33+
}

0 commit comments

Comments
 (0)