LeetCode 3218: Minimum Cost for Cutting Cake I Solution
Master LeetCode problem 3218 (Minimum Cost for Cutting Cake I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3218. Minimum Cost for Cutting Cake I
Problem Explanation
Explanation
To solve this problem, we can first sort the horizontal and vertical cut costs in descending order. Then, we iterate over the sorted costs and calculate the total cost of each cut. We maintain the current number of horizontal and vertical cuts made so far and multiply it with the current cut cost to get the total cost. Finally, we return the sum of all these total costs as the minimum total cost for cutting the cake into 1 x 1 pieces.
- Sort the horizontal and vertical cut costs in descending order.
- Initialize variables to keep track of horizontal and vertical cuts made so far.
- Iterate over the sorted costs to calculate total cost for each cut.
- Return the sum of all total costs as the minimum total cost.
Time complexity: O((m-1)log(m-1) + (n-1)log(n-1))
Space complexity: O(1)
Solution Code
class Solution {
public int minCost(int m, int n, int[] horizontalCuts, int[] verticalCuts) {
Arrays.sort(horizontalCuts);
Arrays.sort(verticalCuts);
long hMax = Math.max(horizontalCuts[0], m - horizontalCuts[horizontalCuts.length - 1]);
long vMax = Math.max(verticalCuts[0], n - verticalCuts[verticalCuts.length - 1]);
for (int i = 1; i < horizontalCuts.length; i++) {
hMax = Math.max(hMax, horizontalCuts[i] - horizontalCuts[i - 1]);
}
for (int i = 1; i < verticalCuts.length; i++) {
vMax = Math.max(vMax, verticalCuts[i] - verticalCuts[i - 1]);
}
return (int)((hMax * vMax) % 1000000007);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3218 (Minimum Cost for Cutting Cake I)?
This page provides optimized solutions for LeetCode problem 3218 (Minimum Cost for Cutting Cake I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3218 (Minimum Cost for Cutting Cake I)?
The time complexity for LeetCode 3218 (Minimum Cost for Cutting Cake I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3218 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3218 in Java, C++, or Python.