Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts in C++

C++Server Side ProgrammingProgramming

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

We have to find the maximum area of a piece of cake after we cut it at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. The answer may be large, so return this modulo 10^9 + 7.

So, if the input is like h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]

then the output will be 4, as from that image we can understand the given rectangular cake.

Red lines are the horizontal and vertical cuts. After we cut the cake, the green piece of cake has the maximum area.

To solve this, we will follow these steps −

  • Define a function mul(), this will take a, b,

  • return ((a mod m) * (b mod m)) mod m

  • From the main method we will take h, w, an array hh, an array vv,

  • sort the array hh and vv

  • insert first element of hh, at index 0 into hh

  • insert h at the end of hh

  • insert first element of vv, at index 0 into vv

  • insert w at the end of vv

  • a := 0, b := 0

  • for initialize i := 1, when i < size of hh, update (increase i by 1), do −

    • a := maximum of a and hh[i] - hh[i - 1]

  • for initialize i := 1, when i < size of vv, update (increase i by 1), do −

    • b := maximum of b and vv[i] - vv[i - 1]

  • return mul(a, b)

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
typedef long long int lli;
class Solution {
public:
   lli mul(lli a, lli b){
      return ((a % mod) * (b % mod)) % mod;
   }
   int maxArea(int h, int w, vector<int>& hh, vector<int>& vv) {
      sort(hh.begin(), hh.end());
      sort(vv.begin(), vv.end());
      hh.insert(hh.begin(), 0);
      hh.push_back(h);
      vv.insert(vv.begin(), 0);
      vv.push_back(w);
      int a = 0;
      int b = 0;
      for (int i = 1; i < hh.size(); i++) {
         a = max(a, hh[i] - hh[i - 1]);
      }
      for (int i = 1; i < vv.size(); i++) {
         b = max(b, vv[i] - vv[i - 1]);
      }
      return mul(a, b);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,4}, v1 = {1,3};
   cout << (ob.maxArea(5,4,v,v1));
}

Input

5,4,{1,2,4}, {1,3}

Output

4
raja
Updated on 18-Nov-2020 10:51:57

Advertisements