Leetcode 3010. Divide an Array Into Subarrays With Minimum Cost I
You are given an array nums
and an integer k
. The array consists of distinct integers into subarrays, such that the result will be reorganized into subarrays, and the cost of dividing the array into those subarrays is minimized. The cost of having a number in a subarray of length x
is x * k
. Write a function minCost
that will compute the minimum cost of the resulting subarrays.
public int minCost(int[] nums, int k)
nums
?k
be zero or negative, or is it always a positive integer?x
is x * k
” mean exactly? Is it the same cost for each number in the subarray?dp[i]
which represents the minimum cost to partition the subarray nums[0...i]
. The transition would be to add a new subarray ending at i
.i
and update the dp[i] as the minimum cost of forming valid subarrays.dp
value correctly.Here is the Java code for solving the problem:
import java.util.Arrays;
public class DivideArray {
public int minCost(int[] nums, int k) {
int n = nums.length;
int[] dp = new int[n + 1];
// Initialize the dp array with infinity
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0; // Base case: cost to partition the first 0 elements is 0
for (int end = 1; end <= n; end++) {
for (int start = 0; start < end; start++) {
int len = end - start;
dp[end] = Math.min(dp[end], dp[start] + len * k);
}
}
return dp[n];
}
public static void main(String[] args) {
DivideArray solution = new DivideArray();
int[] nums = {1, 3, 2, 4};
int k = 10;
System.out.println(solution.minCost(nums, k)); // Example output
}
}
The overall time complexity of this solution is O(n^2)
, where n
is the length of the nums
array. This is because for each index end
, we iterate over all possible start indices to calculate the minimum cost for partition ending there. Given the constraints, this should be efficient enough unless the array size is extremely large.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?