2334. Subarray With Elements Greater Than Varying Threshold

class Solution {
public:
    int validSubarraySize(vector<int>& nums, int threshold)
    {
        nums.push_back(0);
        int n = nums.size();
        stack<int> stk;
        for (int i = 0; i < n; ++i)
        {
            while (!stk.empty() && nums[stk.top()] > nums[i])
            {
                int h = nums[stk.top()]; stk.pop();
                int w = stk.empty() ? i : i - stk.top() - 1;
                if (h * w > threshold)
                {
                    return w;
                }
            }
            stk.push(i);
        }
        return -1;
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)
class Solution {
public:
    int validSubarraySize(vector<int>& nums, int threshold)
    {
        nums.push_back(0);
        int n = nums.size();
        stack<int> stk;
        int i = 0;
        while (i < n)
        {
            if (stk.empty() || nums[i] >= nums[stk.top()])
            {
                stk.push(i);
                ++i;
            }
            else
            {
                int h = nums[stk.top()]; stk.pop();
                int w = stk.empty() ? i : i - stk.top() - 1;
                if (h * w > threshold)
                {
                    return w;
                }
            }
        }
        return -1;
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)