2022-11-25 Daily Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 25

Description

Sum of Subarray Minimums

Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.

 

Example 1:

Input: arr = [3,1,2,4]
Output: 17
Explanation: 
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.

Example 2:

Input: arr = [11,81,94,43,3]
Output: 444

 

Constraints:

  • 1 <= arr.length <= 3 * 104
  • 1 <= arr[i] <= 3 * 104

Solution

seems a problems can be solved with monotonic stack

class Solution {
public:
  int sumSubarrayMins(vector<int>& arr) {
    int len = arr.size();
    if(len == 1) return arr[0];
    vector<int> left(len), right(len);
    vector<pair<int, int>> monoStack;
    vector<pair<int, int>> momoStack;
    for(int i = 0; i < len; ++i) {
      left[i] = i + 1;
      right[i] = len - i;
    }
    for(int i = 0; i < len; ++i) {
      while(monoStack.size() && monoStack.back().first >= arr[i]) {
        monoStack.pop_back();
      }
      left[i] = monoStack.size() ? i - monoStack.back().second : i + 1;
      monoStack.push_back({arr[i], i});

      while(momoStack.size() && momoStack.back().first >= arr[i]) {
        auto pos = momoStack.back().second;
        momoStack.pop_back();
        right[pos] = i - pos;
      }
      momoStack.push_back({arr[i], i});
    }
    long long answer = 0;
    constexpr int MOD = 1e9 + 7;
    for(int i = 0; i < len; ++i) {
      answer += 1LL * right[i] * left[i] * arr[i];
      answer %= MOD;
    }
    return answer;
  }
};

// Accepted
// 87/87 cases passed (100 ms)
// Your runtime beats 95.32 % of cpp submissions
// Your memory usage beats 13.34 % of cpp submissions (44.2 MB)