2547. Minimum Cost to Split an Array

Difficulty:
Related Topics:
Similar Questions:

Problem

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

Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split.

Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed.

The importance value of a subarray is k + trimmed(subarray).length.

Return **the minimum possible cost of a split of **nums.

A subarray is a contiguous non-empty sequence of elements within an array.

  Example 1:

Input: nums = [1,2,1,2,1,3,3], k = 2
Output: 8
Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3].
The importance value of [1,2] is 2 + (0) = 2.
The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6.
The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits.

Example 2:

Input: nums = [1,2,1,2,1], k = 2
Output: 6
Explanation: We split nums to have two subarrays: [1,2], [1,2,1].
The importance value of [1,2] is 2 + (0) = 2.
The importance value of [1,2,1] is 2 + (2) = 4.
The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits.

Example 3:

Input: nums = [1,2,1,2,1], k = 5
Output: 10
Explanation: We split nums to have one subarray: [1,2,1,2,1].
The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10.
The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.

  Constraints:

  .spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0;  } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}

Solution (Java)

class Solution {
    public int minCost(int[] a, int k) {
        int n = a.length;

        // value to index map
        Map<Integer, Integer> M = new HashMap<>();
        int idx = 0;
        for (int i = 0; i < n; i++) {
            int j = M.getOrDefault(a[i], -1);
            if (j == -1) {
                M.put(a[i], idx);
                a[i] = idx++;
            } else a[i] = j;
        }

        int[] dp = new int[n+1];
        for (int i = 1; i <= n; i++) {
            dp[i] = Integer.MAX_VALUE;
            int[] m = new int[idx];
            int score = k;
            for (int j = i-1; j >= 0; j--) {
                if (++m[a[j]] == 2) score += 2;
                else if (m[a[j]] > 2) score++;
                dp[i] = Math.min(dp[i], dp[j] + score);
            }
        }

        return dp[n];
    }        
}

Explain:

nope.

Complexity: