File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ long long subArrayRanges (vector<int >& nums) {
7
+ int64_t result = 0 ;
8
+ vector<int > stk;
9
+ for (int i = 0 ; i <= size (nums); ++i) {
10
+ const int x = (i < size (nums)) ? nums[i] : numeric_limits<int >::max ();
11
+ while (!empty (stk) && nums[stk.back ()] <= x) {
12
+ const int64_t j = stk.back (); stk.pop_back ();
13
+ const int64_t k = !empty (stk) ? stk.back () : -1 ;
14
+ result += nums[j] * (j - k) * (i - j);
15
+ }
16
+ stk.emplace_back (i);
17
+ }
18
+ stk.clear ();
19
+ for (int i = 0 ; i <= size (nums); ++i) {
20
+ const int x = (i < size (nums)) ? nums[i] : numeric_limits<int >::min ();
21
+ while (!empty (stk) && nums[stk.back ()] >= x) {
22
+ const int64_t j = stk.back (); stk.pop_back ();
23
+ const int64_t k = !empty (stk) ? stk.back () : -1 ;
24
+ result -= nums[j] * (j - k) * (i - j);
25
+ }
26
+ stk.emplace_back (i);
27
+ }
28
+ return result;
29
+ }
30
+ };
You can’t perform that action at this time.
0 commit comments