Maximum profit from sale of wines in C++


Problem statement

Given n wines in a row, with integers denoting the cost of each wine respectively. Each year you can sale the first or the last wine in the row. The price of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. On the Yth year, the profit from the ith wine will be Y*Pi. For each year, your task is to print start or end denoting whether first or last wine should be sold. Also, calculate the maximum profit from all the wines.

Example

If wine prices are {2, 4, 6, 2, 5} then output will be:
start end end start start
Maximum profit = 64

Algorithm

We can use dynamic programming to solve this problem −

  • The idea is to store the optimal action for each state and use that to navigate through the optimal states starting from the initial states

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define N 1000
int dp[N][N];
int sell[N][N];
int maxProfitUtil(int price[], int begin, int end, int n) {
   if (dp[begin][end] != -1) {
      return dp[begin][end];
   }
   int year = n - (end - begin);
   if (begin == end) {
      return year * price[begin];
   }
   int x = price[begin] * year + maxProfitUtil(price, begin + 1, end, n);
   int y = price[end] * year + maxProfitUtil(price, begin, end - 1, n);
   int ans = max(x, y);
   dp[begin][end] = ans;
   if (x >= y) {
      sell[begin][end] = 0;
   } else {
      sell[begin][end] = 1;
   }
   return ans;
}
int maxProfit(int price[], int n) {
   for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
         dp[i][j] = -1;
      }
   }
   int ans = maxProfitUtil(price, 0, n - 1, n);
   int i = 0, j = n - 1;
   while (i <= j) {
      if (sell[i][j] == 0) {
         cout << "start ";
         i++;
      } else {
         cout << "end ";
         j--;
      }
   }
   cout << endl;
   return ans;
}
int main() {
   int price[] = { 2, 4, 6, 2, 5 };
   int n = sizeof(price) / sizeof(price[0]);
   int ans = maxProfit(price, n);
   cout << "Maximum profit = " << ans << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

start end end start start
Maximum profit = 64
raja
Published on 21-Jan-2020 11:15:30
Advertisements