Minimum Increment Operations to Make Array Beautiful — LeetCode 2919 Python Solution
- Problem
- #2919
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [2,3,0,0,2], k = 4
- Output
- 3
- Explanation
- We can perform the following increment operations to make nums beautiful:
Python solution
class Solution:
def minIncrementOperations(self, nums: List[int], k: int) -> int:
f = g = h = 0
for x in nums:
f, g, h = g, h, min(f, g, h) + max(k - x, 0)
return min(f, g, h)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2919. Minimum Increment Operations to Make Array Beautiful is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2919. Minimum Increment Operations to Make Array Beautiful?
- LeetCode 2919. Minimum Increment Operations to Make Array Beautiful is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2919. Minimum Increment Operations to Make Array Beautiful?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 2919. Minimum Increment Operations to Make Array Beautiful?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2919. Minimum Increment Operations to Make Array Beautiful cover?
- LeetCode 2919. Minimum Increment Operations to Make Array Beautiful is tagged Array and Dynamic Programming on LeetCode.