1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int minCost(int[] nums, int k) { int n = nums.length; int[] f = new int[n + 1]; Arrays.fill(f, Integer.MAX_VALUE >> 1); f[0] = 0; for (int i = 1; i <= n; ++i) { int[] cnt = new int[n]; int t = 0; for (int j = i - 1; j >= 0; --j) { int x = ++cnt[nums[j]]; if (x == 2) t += 2; else if (x > 2) t += 1; f[i] = Math.min(f[i], t + f[j] + k); } } return f[n]; } }
|