3366. Minimum Array Sum
Medium31.0% acceptance16,370 / 52,814 submissions
Asked by 5 companies
Topics
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
iand dividenums[i]by 2, rounding up to the nearest whole number. You can perform this operation at mostop1times, and not more than once per index. - Operation 2: Choose an index
iand subtractkfromnums[i], but only ifnums[i]is greater than or equal tok. You can perform this operation at mostop2times, 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.
Example 1:
Input: nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1
Output: 23
Explanation:
- Apply Operation 2 to
nums[1] = 8, makingnums[1] = 5. - Apply Operation 1 to
nums[3] = 19, makingnums[3] = 10. - The resulting array becomes
[2, 5, 3, 10, 3], which has the minimum possible sum of 23 after applying the operations.
Example 2:
Input: nums = [2,4,3], k = 3, op1 = 2, op2 = 1
Output: 3
Explanation:
- Apply Operation 1 to
nums[0] = 2, makingnums[0] = 1. - Apply Operation 1 to
nums[1] = 4, makingnums[1] = 2. - Apply Operation 2 to
nums[2] = 3, makingnums[2] = 0. - The resulting array becomes
[1, 2, 0], which has the minimum possible sum of 3 after applying the operations.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 1050 <= k <= 1050 <= op1, op2 <= nums.length
Hints
Hint 1
Think of dynamic programming with states to track progress and remaining operations.
Hint 2
Use
dp[index][op1][op2] where each state tracks progress at index with op1 and op2 operations left.Hint 3
At each state, try applying only operation 1, only operation 2, both in sequence, or skip both to find optimal results.