Skip to content

Commit 701039c

Browse files
authored
Create 1856.Maximum-Subarray-Min-Product.cpp
1 parent f4fb37f commit 701039c

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
typedef long long ll;
2+
class Solution {
3+
ll M = 1e9+7;
4+
public:
5+
int maxSumMinProduct(vector<int>& nums)
6+
{
7+
int n = nums.size();
8+
9+
vector<ll>nextSmaller(n, n);
10+
vector<ll>prevSmaller(n, -1);
11+
12+
stack<ll>Stack;
13+
for (int i=0; i<n; i++)
14+
{
15+
while (!Stack.empty() && nums[Stack.top()]>nums[i])
16+
{
17+
nextSmaller[Stack.top()] = i;
18+
Stack.pop();
19+
}
20+
Stack.push(i);
21+
}
22+
23+
while (!Stack.empty()) Stack.pop();
24+
for (int i=n-1; i>=0; i--)
25+
{
26+
while (!Stack.empty() && nums[Stack.top()]>nums[i])
27+
{
28+
prevSmaller[Stack.top()] = i;
29+
Stack.pop();
30+
}
31+
Stack.push(i);
32+
}
33+
34+
vector<ll>presum(n);
35+
presum[0] = nums[0];
36+
for (int i=1; i<n; i++)
37+
presum[i] = presum[i-1]+nums[i];
38+
39+
ll ret = 0;
40+
for (int i=0; i<n; i++)
41+
{
42+
ll a = prevSmaller[i]==-1 ? 0: presum[prevSmaller[i]];
43+
ll b = presum[nextSmaller[i]-1];
44+
ret = max(ret, (b-a)*(ll)nums[i]);
45+
}
46+
return ret%M;
47+
}
48+
};

0 commit comments

Comments
 (0)