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.
Input: Price of wines: 2 4 6 2 5 Output: beg end end beg beg 64 Explanation :
Approach : It is a standard Dynamic Programming problem. It initially looks like a greedy problem in which we should sell the cheaper of the wines each year but the example case (year 2) clearly proves the approach is wrong. Sometimes we need to sell an expensive wine earlier to save relatively costly wines for later years (Here, if 4 was sold in the 2nd year, in the 4th year we had to sell 2 which would be waste of a heavy coefficient).
The second problem is to “store the strategy” to obtain the calculated price which has a fairly standard method that can be used in other problems as well. The idea is to store the optimal action for each state and use that to navigate through the optimal states starting from the initial state.
beg end end beg beg 64
Time Complexity: O(n2)
- Maximum profit by buying and selling a share at most twice
- Maximum profit by buying and selling a share at most k times
- Maximum value with the choice of either dividing or considering as it is
- Maximum size subset with given sum
- Maximum Sum Decreasing Subsequence
- Maximum sum such that no two elements are adjacent | Set 2
- Maximum subarray sum in O(n) using prefix sum
- Maximum Sum Subsequence of length k
- Size of The Subarray With Maximum Sum
- Maximum Product Cutting | DP-36
- Maximum sum Bi-tonic Sub-sequence
- Maximum length of segments of 0's and 1's
- Maximum path sum in a triangle.
- Longest subarray having maximum sum
- Maximum sum rectangle in a 2D matrix | DP-27
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.