LeetCode 2919: Minimum Increment Operations to Make Array Beautiful
Problem Description
Explanation
To make the array beautiful, we need to ensure that for any subarray of size 3 or more, the maximum element is greater than or equal to k
. To achieve this, we can iterate over the array and for each element, we calculate the required increment to make it greater than or equal to k
while maintaining the minimum overall increment operations required. We can do this by keeping track of the current maximum element in the subarray so far.
Algorithm
- Initialize
ops
to 0 to keep track of the total increment operations needed. - Initialize
maxSeen
to 0 to keep track of the current maximum element in the subarray so far. - Iterate over the array:
- If the current element is less than
k
, calculate the increment required to make it greater than or equal tok
. - If the current element is greater than or equal to
k
, updatemaxSeen
. - Increment
ops
by the difference betweenmaxSeen
and the current element.
- If the current element is less than
- Return
ops
.
Time Complexity
The time complexity of this algorithm is O(n), where n is the length of the input array.
Space Complexity
The space complexity of this algorithm is O(1) as we are using only a constant amount of extra space.
Solutions
class Solution {
public int minOperations(int[] nums, int k) {
int ops = 0;
int maxSeen = 0;
for (int num : nums) {
if (num < k) {
ops += k - num;
} else {
maxSeen = Math.max(maxSeen, num);
}
ops += Math.max(0, maxSeen - num);
}
return ops;
}
}
Loading editor...