File tree Expand file tree Collapse file tree
Stack/1856.Maximum-Subarray-Min-Product Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments