Problem
You are given an integer array nums
and three integers k
, op1
, and
op2
.
You can perform the following operations on nums
:
- Operation 1 : Choose an index
i
and dividenums[i]
by 2, rounding up to the nearest whole number. You can perform this operation at mostop1
times, and not more than once per index. - Operation 2 : Choose an index
i
and subtractk
fromnums[i]
, but only ifnums[i]
is greater than or equal tok
. You can perform this operation at mostop2
times, and not more than once per index.
Note: Both operations can be applied to the same index, but at most once each.
Return the minimum possible sum of all elements in nums
after performing any number of operations.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 100
0 <= nums[i] <= 10^5
0 <= k <= 10^5
0 <= op1, op2 <= nums.length
Solution
Method 1 – Dynamic Programming with State Compression
Intuition
Each operation can be applied at most once per index, and both can be applied to the same index. We want to minimize the sum by choosing which operation(s) to apply to each index, given the limits. This is a classic DP problem with state compression: for each index, track the number of op1 and op2 used, and the minimum sum achievable.
Approach
- Use DP with states (i, op1_used, op2_used) representing the minimum sum for the first i elements, using op1_used and op2_used operations.
- For each index, try:
- No operation.
- Only op1 (divide by 2, round up).
- Only op2 (subtract k if possible).
- Both operations (divide by 2, then subtract k if possible).
- Update DP accordingly, ensuring not to exceed op1/op2 limits and not to apply more than once per index.
- The answer is the minimum sum over all valid states after processing all elements.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n * op1 * op2)
- DP over n elements and op1/op2 states.
- 🧺 Space complexity:
O(n * op1 * op2)
- For DP cache.