LeetCode-in-Java

4041. Minimum Operations to Form Subset Sum II

Hard

You are given an integer array nums and an integer sum.

In one operation, choose an element with current value x and replace it with either 2 * x or floor(x / 2).

For each element, multiplication and division operations may be performed in any order.

Return the minimum number of operations needed so that some subset of the resulting array has a sum exactly equal to sum. If it is impossible, return -1.

The floor() function returns the integer part of the division.

Example 1:

Input: nums = [10,2], sum = 13

Output: 3

Explanation:

Example 2:

Input: nums = [6,3], sum = 8

Output: 2

Explanation:

Example 3:

Input: nums = [2,2], sum = 7

Output: -1

Explanation:

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    private static final int INF = (int) 1e9;

    public int minOperations(int[] nums, int sum) {
        int[] dp = new int[sum + 1];
        Arrays.fill(dp, INF);
        dp[0] = 0;
        for (int num : nums) {
            int[] cost = new int[sum + 1];
            Arrays.fill(cost, INF);
            int v = num;
            int k = 0;
            while (v > 0) {
                int t = v;
                int m = 0;
                while (t <= sum) {
                    if (k + m < cost[t]) {
                        cost[t] = k + m;
                    }
                    t *= 2;
                    m++;
                }
                v /= 2;
                k++;
            }
            int[] ndp = dp.clone();
            for (int t = 1; t <= sum; t++) {
                int c = cost[t];
                if (c >= INF) {
                    continue;
                }
                for (int j = sum; j >= t; j--) {
                    int cur = dp[j - t] + c;
                    if (cur < ndp[j]) {
                        ndp[j] = cur;
                    }
                }
            }
            dp = ndp;
            if (dp[sum] == 0) {
                return 0;
            }
        }
        return dp[sum] >= INF ? -1 : dp[sum];
    }
}