LeetCode-in-Java

4040. Minimum Operations to Form Subset Sum I

Medium

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, all multiplication operations performed on it must occur before any division operations performed on it.

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 = [5,6,10], sum = 4

Output: 3

Explanation:

Example 2:

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

Output: 3

Explanation:

Example 3:

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

Output: -1

Explanation:

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    private static final int INF = 1000000;

    public int minOperations(int[] nums, int sum) {
        int[] dp = new int[sum + 1];
        Arrays.fill(dp, INF);
        dp[0] = 0;
        for (int x : nums) {
            int[] next = dp.clone();
            long value = x;
            int cost = 0;
            while (value <= sum) {
                int v = (int) value;
                for (int s = v; s <= sum; s++) {
                    if (dp[s - v] != INF) {
                        next[s] = Math.min(next[s], dp[s - v] + cost);
                    }
                }
                value *= 2;
                cost++;
            }
            value = x;
            cost = 0;
            while (value > 1) {
                value /= 2;
                cost++;
                int v = (int) value;
                for (int s = v; s <= sum; s++) {
                    if (dp[s - v] != INF) {
                        next[s] = Math.min(next[s], dp[s - v] + cost);
                    }
                }
            }
            dp = next;
        }
        return dp[sum] == INF ? -1 : dp[sum];
    }
}