#3420

Count Non-Decreasing Subarrays After K Operations

Hard
ArrayStackSegment TreeQueueSliding WindowMonotonic StackMonotonic QueueTwo PointersSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a two-pointer technique to efficiently count valid subarrays. This approach reduces the time complexity significantly by avoiding redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, left and right, both at the start of the array.
  2. 2Step 2: Expand the right pointer to include elements in the current subarray while maintaining the count of operations needed to make it non-decreasing.
  3. 3Step 3: If the operations exceed k, increment the left pointer to reduce the size of the subarray until operations are within k.
  4. 4Step 4: For each valid subarray, count the number of subarrays that can be formed with the current right pointer.
solution.py13 lines
1def countNonDecreasingSubarrays(nums, k):
2    count = 0
3    left = 0
4    operations = 0
5    for right in range(len(nums)):
6        if right > 0 and nums[right] < nums[right - 1]:
7            operations += (nums[right - 1] - nums[right])
8        while operations > k:
9            if left < right and nums[left] < nums[left + 1]:
10                operations -= (nums[left + 1] - nums[left])
11            left += 1
12        count += (right - left + 1)
13    return count

Complexity note: The time complexity is O(n) because each element is processed at most twice (once by the right pointer and once by the left pointer).

  • 1Using two pointers can significantly reduce the time complexity.
  • 2Understanding how to maintain a running count of operations is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.