Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create wine_problem.cpp #511

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions Advanced/CPP/wine_problem.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
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. However, 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 “beg” or “end” denoting whether first or
last wine should be sold. Also, calculate the maximum profit from all the wines.
*/

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

#define N 1000

int dp[N][N];

// This array stores the "optimal action"
// for each state i, j
int sell[N][N];

// Function to maximize profit
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];

// x = maximum profit on selling the
// wine from the front this year
int x = price[begin] * year +
maxProfitUtil(price, begin + 1, end, n);

// y = maximum profit on selling the
// wine from the end this year
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;
}

// Util Function to calculate maxProfit
int maxProfit(int price[], int n) {
// reseting the dp table
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) {
// sell[i][j]=0 implies selling the
// wine from beginning will be more
// profitable in the long run
if (sell[i][j] == 0) {
cout << "beg ";
i++;
} else {
cout << "end ";
j--;
}
}

cout << endl;

return ans;
}

int main() {
// Price array
int price[] = { 2, 4, 6, 2, 5 };

int n = sizeof(price) / sizeof(price[0]);

int ans = maxProfit(price, n);

cout << ans << endl;

return 0;
}