LeetCode-in-Java

3489. Zero Array Transformation IV

Medium

You are given an integer array nums of length n and a 2D array queries, where queries[i] = [li, ri, vali].

Each queries[i] represents the following action on nums:

A Zero Array is an array with all its elements equal to 0.

Return the minimum possible non-negative value of k, such that after processing the first k queries in sequence, nums becomes a Zero Array. If no such k exists, return -1.

Example 1:

Input: nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]

Output: 2

Explanation:

Example 2:

Input: nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]

Output: -1

Explanation:

It is impossible to make nums a Zero Array even after all the queries.

Example 3:

Input: nums = [1,2,3,2,1], queries = [[0,1,1],[1,2,1],[2,3,2],[3,4,1],[4,4,1]]

Output: 4

Explanation:

Example 4:

Input: nums = [1,2,3,2,6], queries = [[0,1,1],[0,2,1],[1,4,2],[4,4,4],[3,4,1],[4,4,5]]

Output: 4

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    private int solve(int[][] q, int i, int target, int k, int[][] dp) {
        // we found  a valid sum equal to target so return current index of query.
        if (target == 0) {
            return k;
        }
        // return a larger number to invalidate this flow
        if (k >= q.length || target < 0) {
            return q.length + 1;
        }
        if (dp[target][k] != -1) {
            return dp[target][k];
        }
        // skip current query val
        int res = solve(q, i, target, k + 1, dp);
        // pick the val if its range is in the range of target index
        if (q[k][0] <= i && i <= q[k][1]) {
            res = Math.min(res, solve(q, i, target - q[k][2], k + 1, dp));
        }
        dp[target][k] = res;
        return res;
    }

    public int minZeroArray(int[] nums, int[][] queries) {
        int ans = -1;
        for (int i = 0; i < nums.length; ++i) {
            int[][] dp = new int[nums[i] + 1][queries.length];
            Arrays.stream(dp).forEach(row -> Arrays.fill(row, -1));
            ans = Math.max(ans, solve(queries, i, nums[i], 0, dp));
        }
        return (ans > queries.length) ? -1 : ans;
    }
}