Input: m =3, n =2, horizontalCut =[1,3], verticalCut =[5]Output: 13Explanation:
* Perform a cut on the vertical line 0with cost 5, current total cost is5.* Perform a cut on the horizontal line 0 on `3 x 1` subgrid with cost 1.* Perform a cut on the horizontal line 0 on `3 x 1` subgrid with cost 1.* Perform a cut on the horizontal line 1 on `2 x 1` subgrid with cost 3.* Perform a cut on the horizontal line 1 on `2 x 1` subgrid with cost 3.The total cost is`5 + 1 + 1 + 3 + 3 = 13`.
Input: m =2, n =2, horizontalCut =[7], verticalCut =[4]Output: 15Explanation:
* Perform a cut on the horizontal line 0with cost 7.* Perform a cut on the vertical line 0 on `1 x 2` subgrid with cost 4.* Perform a cut on the vertical line 0 on `1 x 2` subgrid with cost 4.The total cost is`7 + 4 + 4 = 15`.
To minimize the total cost, always cut the highest cost line available. Each cut increases the number of pieces in the other direction, so prioritize the most expensive cuts to maximize their multiplication effect.
classSolution {
funminCost(horizontalCut: IntArray, verticalCut: IntArray): Int {
horizontalCut.sortDescending()
verticalCut.sortDescending()
var h = 1var v = 1var i = 0var j = 0var ans = 0while (i < horizontalCut.size && j < verticalCut.size) {
if (horizontalCut[i] >= verticalCut[j]) {
ans += horizontalCut[i] * v
h++ i++ } else {
ans += verticalCut[j] * h
v++ j++ }
}
while (i < horizontalCut.size) {
ans += horizontalCut[i] * v
i++ }
while (j < verticalCut.size) {
ans += verticalCut[j] * h
j++ }
return ans
}
}
defmin_cost(horizontal_cut: list[int], vertical_cut: list[int]) -> int:
horizontal_cut.sort(reverse=True)
vertical_cut.sort(reverse=True)
h, v =1, 1 i, j =0, 0 ans =0while i < len(horizontal_cut) and j < len(vertical_cut):
if horizontal_cut[i] >= vertical_cut[j]:
ans += horizontal_cut[i] * v
h +=1 i +=1else:
ans += vertical_cut[j] * h
v +=1 j +=1while i < len(horizontal_cut):
ans += horizontal_cut[i] * v
i +=1while j < len(vertical_cut):
ans += vertical_cut[j] * h
j +=1return ans
impl Solution {
pubfnmin_cost(horizontal_cut: Vec<i32>, vertical_cut: Vec<i32>) -> i32 {
letmut hcut = horizontal_cut;
letmut vcut = vertical_cut;
hcut.sort_by(|a, b| b.cmp(a));
vcut.sort_by(|a, b| b.cmp(a));
let (mut h, mut v) = (1, 1);
let (mut i, mut j) = (0, 0);
letmut ans =0;
while i < hcut.len() && j < vcut.len() {
if hcut[i] >= vcut[j] {
ans += hcut[i] * v asi32;
h +=1;
i +=1;
} else {
ans += vcut[j] * h asi32;
v +=1;
j +=1;
}
}
while i < hcut.len() {
ans += hcut[i] * v asi32;
i +=1;
}
while j < vcut.len() {
ans += vcut[j] * h asi32;
j +=1;
}
ans
}
}