lc2334 元素值大于变化阈值的子数组

给定数组nums[n]和整数threshold,找到长度为k的子数组,满足子数组中每个元素都大于threshold/k,返回满足条件的任意一个k即可,如不存在,返回-1。
1<=n<=1e5; 1<=nums[i],threshold<=1e9

子数组每个元素都大于t,也就是最小值大于t。对于固定的最小值,显然子数组越长越有可能满足条件,因此考虑每个元素作为最小值的情况,尽可能的往两边延伸,判断是否能成为答案。使用半开半闭区间避免重复统计。

class Solution {
public:
    int validSubarraySize(vector<int>& nums, int threshold) {
        int n = nums.size();
        vector<int> L(n), R(n), s;
        for (int i = 0; i < n; i++) {
            while (!s.empty() && nums[i] <= nums[s.back()])
                s.pop_back();
            L[i] = s.empty() ? -1 : s.back();
            s.push_back(i);
        }
        s.clear();
        for (int i = n-1; i >= 0; i--) {
            while (!s.empty() && nums[i] < nums[s.back()])
                s.pop_back();
            R[i] = s.empty() ? n : s.back();
            s.push_back(i);
        }
        for (int i = 0; i < n; i++) {
            if (1LL * nums[i] * (R[i]-L[i]-1) > threshold)
                return R[i]-L[i]-1;
        }
        return -1;
    }
};
posted @ 2024-03-17 14:13  chenfy27  阅读(5)  评论(0编辑  收藏  举报