Skip to content

Commit 33ffa9a

Browse files
authored
Update 1856-maximum-subarray-min-product.js
1 parent a010bd2 commit 33ffa9a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

1856-maximum-subarray-min-product.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,50 @@ function bigint_max(...args){
4444
args.forEach(a=>{if (a > m) {m = a}});
4545
return m;
4646
}
47+
48+
// another
49+
50+
/**
51+
* @param {number[]} nums
52+
* @return {number}
53+
*/
54+
const maxSumMinProduct = function(nums) {
55+
const n = nums.length, s1 = [], s2 = [],
56+
left = Array(n), right = Array(n), mod = BigInt(1e9 + 7)
57+
for(let i = 0; i < n; i++) {
58+
while(s1.length && nums[s1[s1.length - 1]] >= nums[i]) s1.pop()
59+
if(s1.length) left[i] = s1[s1.length - 1] + 1
60+
else left[i] = 0
61+
s1.push(i)
62+
}
63+
64+
for(let i = n - 1; i >= 0; i--) {
65+
while(s2.length && nums[s2[s2.length - 1]] >= nums[i]) s2.pop()
66+
if(s2.length) right[i] = s2[s2.length - 1] - 1
67+
else right[i] = n - 1
68+
s2.push(i)
69+
}
70+
71+
const preSum = Array(n)
72+
for(let i = 0; i < n; i++) {
73+
preSum[i] = (i === 0 ? 0n : preSum[i - 1]) + BigInt(nums[i])
74+
}
75+
let res = 0n
76+
for(let i = 0; i < n; i++) {
77+
res = max(res, getSum(preSum, left[i], right[i]) * BigInt(nums[i]))
78+
}
79+
return res % mod
80+
81+
};
82+
83+
function getSum(arr, l, r) {
84+
return arr[r] - (l === 0 ? 0n : arr[l - 1])
85+
}
86+
87+
function max(...args) {
88+
let res = -Infinity
89+
for(let e of args) {
90+
if(e > res) res = e
91+
}
92+
return res
93+
}

0 commit comments

Comments
 (0)