Intuition¶
The goal is to cut a cake into $1 \times 1$ pieces with the minimum cost. Each cut has a cost associated with it, and the cost is fixed regardless of the size of the piece being cut. The key to minimizing the total cost is to make the most expensive cuts first when they will affect the largest number of subsequent cuts. In this case we can use dynamic programming or greedy algorithm to solve the problem
Approach 1: Dynamic Programming¶
Updating...
Approach 2: Greedy¶
Explanation:¶
- Sort Cuts in Descending Order:
-
Sort the
hCutandvCutarrays in descending order. This allows us to consider the most expensive cuts first. -
Initialize Counters and Cost:
- Use two counters:
hCountto keep track of the number of horizontal segments andvCountfor the number of vertical segments. Initialize both to 1. - Initialize
iandjto 0 to traverse thehCutandvCutarrays respectively. -
Initialize
costto accumulate the total cost of cuts. -
Process Cuts in Descending Order:
- Use a while loop to process both
hCutandvCutarrays. -
Compare the current highest cost from both arrays:
- If the horizontal cut is more expensive, make this cut. The cost is added as
hCut[i] * vCount, then incrementiandhCount. - If the vertical cut is more expensive or equal, make this cut. The cost is added as
vCut[j] * hCount, then incrementjandvCount.
- If the horizontal cut is more expensive, make this cut. The cost is added as
-
Process Remaining Cuts:
-
After the main loop, there may be remaining cuts in either
hCutorvCut. Process these remaining cuts, multiplying by the current count of vertical or horizontal segments. -
Return the Total Cost:
- The accumulated
costrepresents the minimum total cost to cut the entire cake into (1 \times 1) pieces.
Complexity¶
- Time complexity: $O((m + n) \log (m + n))$ due to sorting the cut arrays.
- Space complexity: $O(1)$ as we are using a constant amount of extra space.
Code¶
class Solution {
public:
int minimumCost(int m, int n, vector<int>& hCut, vector<int>& vCut) {
sort(hCut.begin(), hCut.end(), greater());
sort(vCut.begin(), vCut.end(), greater());
int i = 0, j = 0;
int hCount = 1, vCount = 1;
int cost = 0;
while (i < hCut.size() && j < vCut.size()) {
if (hCut[i] > vCut[j]) {
cost += hCut[i++] * vCount;
++hCount;
}
else {
cost += vCut[j++] * hCount;
++vCount;
}
}
while (i < hCut.size()) {
cost += hCut[i++] * vCount;
}
while (j < vCut.size()) {
cost += vCut[j++] * hCount;
}
return cost;
}
};