Count Subarrays With Cost Less Than or Equal to K

You are given an integer array nums and an integer k.

For any subarray nums[l..r], its cost is defined as: cost = (maximum_element - minimum_element) * length_of_subarray where length_of_subarray is r - l + 1.

Return the total number of subarrays whose cost is less than or equal to k.

Example 1:

Input: nums = [1, 2, 3], k = 3

Output: 5

Explanation:

The valid subarrays are [1], [2], [3] (cost 0), [1, 2] (cost 2), and [2, 3] (cost 2). The subarray [1, 2, 3] has a cost of (3 - 1) * 3 = 6, which exceeds 3.

Example 2:

Input: nums = [10, 1, 10], k = 10

Output: 3

Explanation:

Only the single-element subarrays [10], [1], and [10] have a cost of 0, which is less than or equal to 10. The length 2 subarrays [10, 1] and [1, 10] both have a cost of (10 - 1) * 2 = 18, and the length 3 subarray [10, 1, 10] has a cost of (10 - 1) * 3 = 27.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [4, 4, 2, 4], k = 5

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 0 <= k <= 1015

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long countSubarrays(vector<int>& nums, long long k) {
}
};
Test Case

Input:

K
Nums