Leetcode 3010. Divide an Array Into Subarrays With Minimum Cost I
Given an integer array nums and an integer k, you need to divide the array into exactly k non-empty subarrays such that the cost is minimized. The cost of a subarray is the square of its length. The total cost is the sum of the costs of the individual subarrays.
Your task is to implement a function that finds the minimum possible total cost.
int minCost(vector<int>& nums, int k);
Input: nums = [1, 2, 1, 2, 1, 2], k = 3
Output: 1
Explanation: We can divide the array as [1,2], [1,2], [1,2]. The cost is 2^2 + 2^2 + 2^2 = 4 + 4 + 4 = 12
nums and the value of k?
nums ranges from 1 to 1000, and values for k range from 1 to nums.size().nums?
We will use a dynamic programming approach to solve this problem.
Define DP State:
Define dp[i][j] as the minimum cost to divide the first i elements into j subarrays.
Base Case:
dp[0][0] = 0, because the cost of dividing zero elements into zero subarrays is zero.
i (from 1 to n) and j (from 1 to k):
m (from 0 to i-1), and calculate the cost of making a subarray from m+1 to i.[m+1, i] will be (i - m) * (i - m).dp[i][j] as the minimum of its current value and dp[m][j-1] + cost of the subarray.dp[n][k] will hold the minimum cost to divide the array into exactly k subarrays.#include <vector>
#include <algorithm>
#include <limits.h>
using namespace std;
int minCost(vector<int>& nums, int k) {
int n = nums.size();
vector<vector<int>> dp(n + 1, vector<int>(k + 1, INT_MAX));
// Base case
dp[0][0] = 0;
// DP array to keep result
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= k; ++j) {
for (int m = 0; m < i; ++m) {
int length_squared = (i - m) * (i - m);
if (dp[m][j-1] != INT_MAX) {
dp[i][j] = min(dp[i][j], dp[m][j-1] + length_squared);
}
}
}
}
return dp[n][k];
}
Space Complexity:
The space complexity is O(n * k) due to the use of the dp table with dimensions (n+1) x (k+1).
Time Complexity:
O(n^2 * k) since for each i and j, we’re iterating over all possible previous indices m.O(n^2 * k).This solution should be efficient enough for the input constraints provided (considering n and k up to 1000).
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?