Problem
You are given a 0-indexed integer array nums
having length n
, and an integer k
.
You can perform the following increment operation any number of times (including zero):
- Choose an index
i
in the range[0, n - 1]
, and increasenums[i]
by1
.
An array is considered beautiful if, for any subarray with a size of
3
or more , its maximum element is greater than or equal to k
.
Return _an integer denoting theminimum number of increment operations needed to make _nums
beautiful.
A subarray is a contiguous non-empty sequence of elements within an array.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
3 <= n == nums.length <= 10^5
0 <= nums[i] <= 10^9
0 <= k <= 10^9
Solution
Method 1 – Sliding Window with Greedy Increment
Intuition
For every subarray of length 3, its maximum must be at least k. To minimize increments, we can use a sliding window of size 3 and ensure that at least one element in each window is at least k. We greedily increment the rightmost element in each window if needed, so that all overlapping windows are covered with minimal operations.
Approach
- Iterate through the array with a sliding window of size 3.
- For each window, check if its maximum is at least k.
- If not, increment the rightmost element in the window to reach k, and count the operations.
- Continue to the next window, always updating the array as you go.
- Return the total number of operations performed.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the length of nums. Each window is checked once. - 🧺 Space complexity:
O(n)
, for the working array.