Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts LeetCode Solution - The Coding Shala

Home >> LeetCode >> Maximum area of a piece of cake after horizontal and vertical cuts

 In this post, we will learn how to solve LeetCode's Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts Problem and will implement its solution in Java.

Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts Problem

Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.

Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a huge number, return this modulo 10^9 + 7.

Example 1:
Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4 

Practice this problem on LeetCode.

LeetCode - Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts Java Solution

Approach 1

Here we need to find the maximum gap between two cuts both horizontally and vertically then return their product. The steps are as below.

Step 1. Sort both the arrays.

Step 2. Find the maximum difference between the two cuts.

Step 3. Return the product of maximum differences with modulo 1000000007

Java Program: 

class Solution {
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        
        long maxH = 0;
        long maxV = 0;
        
        // maximum horizontal difference
        maxH = Math.max(horizontalCuts[0] - 0, h - horizontalCuts[horizontalCuts.length-1]);
        for (int i = 1; i < horizontalCuts.length; i++) {
            maxH = Math.max(maxH, horizontalCuts[i] - horizontalCuts[i-1]);
        }
        
        // maximum veritcal difference
        maxV = Math.max(verticalCuts[0] - 0, w - verticalCuts[verticalCuts.length-1]);
        for (int i = 1; i < verticalCuts.length; i++) {
            maxV = Math.max(maxV, verticalCuts[i] - verticalCuts[i-1]);
        }
        
        long res = (maxH * maxV) % 1000000007;
        
        return (int) res;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala