#2919

Minimum Increment Operations to Make Array Beautiful

Medium
ArrayDynamic ProgrammingSliding WindowGreedy Approach
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 sliding window approach to ensure that every subarray of size 3 has at least one element greater than or equal to k. We only need to check the last element of each window and adjust accordingly, minimizing the number of increments.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to count increments and iterate through the array from index 0 to n-1.
  2. 2Step 2: For each index, check if the current element is less than k.
  3. 3Step 3: If it is, calculate how much to increment it to reach k and add that to the increments count.
  4. 4Step 4: Adjust the next two elements in the window to ensure they are also at least k.
solution.py11 lines
1def minIncrementForBeautiful(nums, k):
2    increments = 0
3    n = len(nums)
4    for i in range(n):
5        if nums[i] < k:
6            increments += k - nums[i]
7            if i + 1 < n:
8                nums[i + 1] = max(nums[i + 1], k)
9            if i + 2 < n:
10                nums[i + 2] = max(nums[i + 2], k)
11    return increments

Complexity note: This complexity is linear because we only make a single pass through the array, adjusting values as necessary.

  • 1To ensure every subarray of size 3 has a maximum >= k, at least one element in each subarray must be adjusted.
  • 2Increment operations should be minimized by focusing on the last element of each sliding window.

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