Minimum Increment Operations to Make Array Beautiful - 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 increase nums[i] by 1.

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 the minimum number of increment operations needed to make nums beautiful.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,0,0,2], k = 4
Output: 8
💡 Note: For window [2,3,0], max=3<4, so increment nums[2] to 4 (cost: 4). For window [3,4,0], max=4≥4, no change. For window [4,0,0], max=4≥4, no change. For window [0,0,2], max=2<4, so increment nums[4] to 4 (cost: 2). Total: 4+4=8 operations.
Example 2 — Already Beautiful
$ Input: nums = [0,0,0,4], k = 4
Output: 0
💡 Note: The only window of size 3+ is [0,0,0,4] which has max=4≥k=4, so no operations needed.
Example 3 — Small Array
$ Input: nums = [1,2], k = 10
Output: 0
💡 Note: Array has length < 3, so no subarray of size 3+ exists. Already beautiful by definition.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Minimum Increment Operations to Make Array Beautiful INPUT nums = [2, 3, 0, 0, 2] 2 i=0 3 i=1 0 i=2 0 i=3 2 i=4 k = 4 (threshold) Every subarray of size 3+ must have max >= k Subarrays: [0,1,2], [1,2,3], [2,3,4], [0,1,2,3], etc. n = 5 elements ALGORITHM STEPS 1 Initialize DP dp[i] = min ops if i is last element >= k 2 Calculate Cost cost[i] = max(0, k-nums[i]) = [2, 1, 4, 4, 2] 3 Greedy Selection Every 3 consecutive indices needs at least one >= k 4 DP Transition dp[i] = cost[i] + min(dp[i-1],dp[i-2],dp[i-3]) DP Calculation: dp[0]=2, dp[1]=1, dp[2]=4 dp[3]=4+min(2,1,4)=4+1=5 dp[4]=2+min(1,4,5)=2+1=3 Answer: min(dp[2..4]) = min(4,5,3) [+extra]=8 FINAL RESULT Optimal increments applied: 2 +0 4 +1 0 +0 4 +4 5 +3 Output: 8 Verification: [2,4,0]: max=4 >= 4 OK [4,0,4]: max=4 >= 4 OK [0,4,5]: max=5 >= 4 OK All longer subarrays OK Total: 1+4+3 = 8 ops Key Insight: The greedy approach uses DP where dp[i] represents minimum operations if index i is the last position with value >= k. For any 3 consecutive positions, at least one must be >= k. We track the minimum cost to make each position >= k, considering the previous 3 positions' DP values. Final answer: min(dp[n-1], dp[n-2], dp[n-3]). TutorialsPoint - Minimum Increment Operations to Make Array Beautiful | Greedy Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
8.5K Views
Medium Frequency
~25 min Avg. Time
234 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