Problem
You are given a 0-indexed integer array nums
and a positive integer k
.
You can apply the following operation on the array any number of times:
- Choose any subarray of size
k
from the array and decrease all its elements by1
.
Return true
if you can make all the array elements equal to0
,orfalse
otherwise.
A subarray is a contiguous non-empty part of an array.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= k <= nums.length <= 10^5
0 <= nums[i] <= 10^6
Solution
Method 1 – Greedy with Prefix Sum
Intuition
The key idea is to always reduce the leftmost non-zero element as much as possible using the allowed operation. By greedily applying the operation starting from the left, and tracking the cumulative effect of all operations using a prefix sum (difference array), we can efficiently determine if it’s possible to make all elements zero.
Approach
- Initialize a difference array
diff
of sizen+1
(wheren
is the length ofnums
) to track the net effect of operations. - Iterate through the array from left to right.
- At each index
i
, update the running sum of operations applied so far. - If after applying all previous operations,
nums[i]
is still greater than zero:- If there are at least
k
elements remaining fromi
, apply the operation enough times to makenums[i]
zero. - Update the difference array to reflect this operation.
- If not enough elements remain, return
False
.
- If there are at least
- If the loop completes, return
True
.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— Each element is processed once. - 🧺 Space complexity:
O(n)
— For the difference array.