Best Time to Buy and Sell
You are given an array(PRICES) of stock prices for N consecutive days. Your task is to find the maximum profit that you can make by completing as many transactions as you like, where a transaction denotes buying one and selling one share of the stock.
You must sell the stock before you buy it again.
The first line of input contains an integer value N, denoting the size of the input array. The second line contains N single space-separated integers, denoting the prices on each day.
The only output line contains an integer, denoting the maximum profit.
You are not required to print the output, it has already been taken care of. Just implement the function.
1 <= N <= 5 * 10^4 0 <= PRICES[i] <= 10^4 Time Limit: 1sec
In this approach, we will be using recursion, where we will have a recursive method let's say MAX_PROFIT(PRICES, START) to find the maximum profit that we can make by doing any number of transactions starting from the START index.
To calculate this we will iterate on our prices starting from PRICES[START] till the last price. We will let the current price as the start of a transaction(buy price) and for each START, we will iterate over the next remaining prices and consider them as the end of the transaction(sell price). Let’s say the sell index ends. So the profit for this transaction is profit is PRICES[END] - PRICES[START]. Let it be equal to CURPROFIT (remember we will only choose that END index having price greater than the price of the START index. ).
Now we will calculate the maximum profit possible for the days after the ending day of the current transaction using recursion. So the PROFIT = CURPROFIT + MAX_PROFIT(PRICES, END + 1) and we will find the maximum of all possible profits.
int MAX_PROFIT(PRICES, START):
- If there are no prices left to consider, Return.
- Initialize MAX with zero.
- For all prices i.e i from START to the SIZE - 1 index, where size denotes the size of the prices array. Buy the stock(start transaction).
- Initialize MAXPROFIT with zero.
- For remaining prices, j from i + 1 to SIZE - 1, Sell the stock(end transaction) if PRICE[j] > PRICE[i],
- CURPROFIT = PRICE[j] - PRICE[i].
- Calculate the maximum profit for the remaining prices and add to PROFIT, PROFIT += MAX_PROFIT(PRICES, j + 1).
- If PROFIT > MAXPROFIT , MAXPROFIT = PROFIT.
- If MAXPROFIT > MAX, MAX = MAXPROFIT.
- Return MAX.