C++ Program to find out the maximum amount of profit that can be achieved from selling wheat


Suppose, there is n number of cities that are connected with m roads. The roads are unidirectional, the roads can only go from source to destination and not the opposite. The roads are given in the array 'roads' in format {source, destination}. Now, in the cities, wheat is sold at different prices. The price of wheat across the cities is given in an array 'price', where the i-th value is the price of wheat in the i-th city. Now, a traveler can buy wheat from any of the cities and can reach any of the cities (if it is permissible) and sell it. We have to find out the maximum amount of profit that can be achieved by the traveler by trading wheat.

So, if the input is like n = 5, m = 3, price = {4, 6, 7, 8, 5}, roads = {{1, 2}, {2, 3}, {2, 4}, {4, 5}}, then the output will be 4.

If the traveler buys wheat in the first city and sells it in the fourth city, then the total amount of profit achieved is 4.

Steps

To solve this, we will follow these steps −

Define one 2D array graph of size nxn.
for initialize i := 0, when i < m, update (increase i by 1), do:
   x := first value of roads[i]
   y := second value of roads[i]
   decrease x, y by 1
   insert y at the end of graph[x]
Define an array tp of size n initialized with value negative infinity.
for initialize i := 0, when i < n, update (increase i by 1), do:
   for each value u in graph[i], do:
      tp[u] := minimum of ({tp[u], tp[i], price[i]})
res := negative infinity
for initialize i := 0, when i < n, update (increase i by 1), do:
   res := maximum of (res and price[i] - tp[i])
return res

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int n, int m, vector<int> price, vector<pair<int, int>>
roads){
   vector<vector<int>> graph(n);
   for(int i = 0; i < m; i++){
      int x, y;
      x = roads[i].first;
      y = roads[i].second;
      x--, y--;
      graph[x].push_back(y);
   }
   vector<int> tp(n, int(INFINITY));
   for(int i = 0; i < n; i++){
      for(int u : graph[i]){
         tp[u] = min({tp[u], tp[i], price[i]});
      }
   }
   int res = -int(INFINITY);
   for(int i = 0; i < n; i++){
      res = max(res, price[i] - tp[i]);
   }
   return res;
}
int main() {
   int n = 5, m = 3;
   vector <int> price = {4, 6, 7, 8, 5};
   vector<pair<int, int>> roads = {{1, 2}, {2, 3}, {2, 4}, {4, 5}};
   cout<< solve(n, m, price, roads);
   return 0;
}

Input

5, 3, {4, 6, 7, 8, 5}, {{1, 2}, {2, 3}, {2, 4}, {4, 5}}

Output

4

Updated on: 02-Mar-2022

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements