Count Non-Decreasing Subarrays After K Operations - Problem

You're given an array nums of n integers and an integer k representing the maximum number of operations allowed.

Your goal: Count how many subarrays can be made non-decreasing using at most k operations.

Operations: For each subarray, you can increment any element by 1 up to k times total. Each subarray is considered independently - changes don't carry over.

Non-decreasing: An array where each element is greater than or equal to the previous element (e.g., [1, 2, 2, 5]).

Example: Given nums = [2, 1, 3] and k = 1, the subarray [2, 1] can become [2, 2] with 1 operation, making it non-decreasing.

Input & Output

example_1.py — Basic Case
$ Input: nums = [2, 1, 3], k = 1
› Output: 5
šŸ’” Note: Subarrays that can be made non-decreasing: [2] (0 ops), [1] (0 ops), [3] (0 ops), [2,1] (1 op to make [2,2]), [1,3] (0 ops). Total: 5 subarrays.
example_2.py — No Operations Needed
$ Input: nums = [1, 2, 3], k = 0
› Output: 6
šŸ’” Note: Array is already non-decreasing, so all 6 possible subarrays ([1], [2], [3], [1,2], [2,3], [1,2,3]) require 0 operations.
example_3.py — Edge Case Single Element
$ Input: nums = [5], k = 2
› Output: 1
šŸ’” Note: Only one subarray [5] exists and it's already non-decreasing with 0 operations needed.

Visualization

Tap to expand
Building Non-Decreasing StaircasesOriginal Array: [2, 1, 3, 2]2132Subarray [1,3,2]After Operations (k=2):133+1Operations Calculation:• Element 1: max = 1, operations = 0• Element 3: max = 3, operations = 0• Element 2: max = 3, operations = 3-2 = 1Total operations: 1 ≤ k=2 āœ“ Valid subarray!Step 1: Track running maximumStep 2: Calculate operations neededStep 3: Check if operations ≤ k
Understanding the Visualization
1
Identify Subarray
Consider a contiguous portion of the array as a potential staircase
2
Calculate Operations
For each element, determine how many 'bricks' (increment operations) needed to reach the running maximum height
3
Check Feasibility
If total bricks needed ≤ k, this staircase can be built successfully
Key Takeaway
šŸŽÆ Key Insight: For each subarray, we maintain a running maximum and count operations needed to lift smaller elements to that height. The challenge is doing this efficiently for all O(n²) possible subarrays.

Time & Space Complexity

Time Complexity
ā±ļø
O(n³)

O(n²) subarrays Ɨ O(n) to check each subarray

n
2n
⚠ Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for calculations

n
2n
āœ“ Linear Space

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 109
  • Each subarray is considered independently
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
26.1K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen