|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +// Function to return the maximum profit |
| 5 | +// that can be made after buying and |
| 6 | +// selling the given stocks |
| 7 | +int maxProfit(int price[], int start, int end) |
| 8 | +{ |
| 9 | + |
| 10 | + // If the stocks can't be bought |
| 11 | + if (end <= start) |
| 12 | + return 0; |
| 13 | + |
| 14 | + // Initialise the profit |
| 15 | + int profit = 0; |
| 16 | + |
| 17 | + // The day at which the stock |
| 18 | + // must be bought |
| 19 | + for (int i = start; i < end; i++) { |
| 20 | + |
| 21 | + // The day at which the |
| 22 | + // stock must be sold |
| 23 | + for (int j = i + 1; j <= end; j++) { |
| 24 | + |
| 25 | + // If buying the stock at ith day and |
| 26 | + // selling it at jth day is profitable |
| 27 | + if (price[j] > price[i]) { |
| 28 | + |
| 29 | + // Update the current profit |
| 30 | + int curr_profit = price[j] - price[i] |
| 31 | + + maxProfit(price, start, i - 1) |
| 32 | + + maxProfit(price, j + 1, end); |
| 33 | + |
| 34 | + // Update the maximum profit so far |
| 35 | + profit = max(profit, curr_profit); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return profit; |
| 40 | +} |
| 41 | + |
| 42 | +// Driver code |
| 43 | +int stock() |
| 44 | +{ |
| 45 | + int price[] = { 100, 180, 260, 310, |
| 46 | + 40, 535, 695 }; |
| 47 | + int n = sizeof(price) / sizeof(price[0]); |
| 48 | + |
| 49 | + cout << maxProfit(price, 0, n - 1); |
| 50 | + |
| 51 | + return 0; |
| 52 | +} |
0 commit comments