C++ code to get maximum profit by house making


Suppose we have two numbers n and h, and another array of m triplets T, where T[i] = (li, ri, xi). On a road, there are n places where we can make houses. The spots are numbered as 1 to n. The house height can be from 0 to h. In each spot if we make a house of height k, we will gain k^2 amount of money from it. There are m zone restrictions. The ith restriction says: The tallest house from spots li to ri, must be at most xi. We want to make houses to maximize our profit. We have to find the maximum possible profit we can make. We have to find the maximum profit.

So, if the input is like n = 3; h = 3; T = [[1,1,1],[2,2,3],[3,3,2]], then the output will be 14, because, there are 3 houses, the maximum height is 3, In the first restriction the tallest house between 1 and 1 so it must be 1 at max. In the second restriction the tallest house between 2 and 2 and it must be 3 at max. Similarly in the third restriction the tallest house between 3 and 3 that must be at most 2. So the optimal heights are [1,3,2]. So 1^2 + 3^2 + 2^2 = 14.

Steps

To solve this, we will follow these steps −

m := size of T
Define an array heights n and fill with h
for initialize i := 0, when i < m, update (increase i by 1), do:
   l := T[i, 0]
   r := T[i, 1]
   h := T[i, 2]
   for initialize i := l - 1, when i < r, update (increase i by 1), do:
      heights[i] := minimum of heights[i] and h
ans := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   ans := ans + heights[i] * heights[i]
return ans

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int n, int h, vector<vector<int>> T){
   int l, r;
   int m = T.size();
   vector<int> heights(n, h);
   for (int i = 0; i < m; i++){
      l = T[i][0];
      r = T[i][1];
      h = T[i][2];
      for (int i = l - 1; i < r; i++)
      heights[i] = min(heights[i], h);
   }
   int ans = 0;
   for (int i = 0; i < n; i++)
   ans += heights[i] * heights[i];
   return ans;
}
int main(){
   int n = 3;
   int h = 3;
   vector<vector<int>> T = { { 1, 1, 1 }, { 2, 2, 3 }, { 3, 3, 2 } };
   cout << solve(n, h, T) << endl;
}

Input

3, 3, { { 1, 1, 1 }, { 2, 2, 3 }, { 3, 3, 2 } }

Output

14

Updated on: 30-Mar-2022

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements