Best Time to Buy and Sell Stock

Hi, Are you trading in stocks. Then use this program to generate more returns. It will help you find best time to buy and sell stock to generate maximum returns. Now lets see the problem.
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e., max profit = 0.
Solution
- Ultimate rule to get max return is to buy low and sell high.
- There are two variables we need to track buyprice and sellprice, profit.
- If the price increases we update the sellprice. If the price drops and we calculate the profit and add that to total profit.
- Lets say we have array [7,1,5,3,6,4] we mark buyprice = sellprice = 7 intially. Then price falls to 1, so we update the buy and sell price to 1. Then price increases to 5. Profit is 5-1=4.
- Then price drops to 3, so we add profit 4 to total profit and reset buyprice, sellprice and profit.
[code lang=”java”]
class Solution
{
public int maxProfit(int[] prices)
{
int buyprice = prices[0],profit=0, totalprofit=0,sellprice = prices[0];
for(int i =0 ; i<prices.length; i++)
{
//Price of stock increasing
if(prices[i]>sellprice )
{
profit = prices[i]-buyprice;
sellprice = prices[i];
}
//Price of stock decreasing
if(sellprice>prices[i])
{
//Resetting buyprice and sellprice
buyprice = prices[i];
sellprice = prices[i];
if(profit!=0)
{
totalprofit += profit;
}
profit=0;
}
}
//If stock price not fallen, we finally add the profit to total profit.
if(profit !=0)
{
totalprofit += profit;
}
return totalprofit;
}
}
[/code]
Complexity
Time Complexity – O(n)
Space Complexity – O(1)
Question taken from Leetcode.com | Best time to buy and sell stock
More Problems from Wisdom Overlfow
Check for a pair in array which is equal to sum | Infosys
Triplet Sum in Array | Amazon | Samsung