Header Ads Widget

Trending

6/recent/ticker-posts

Best Time to Buy and sell Stock leetcode

 Problem: Best Time to Buy and Sell Stock - I

We are given an array of prices where Cost[i] is the cost o stock on a particular day.
We have to find the best time to buy and sell stock to get maximum profit.


Input: prices = [7,1,5,3,9,4]
Output: 8


Explanation:- We can maximize our profit in this example, we should buy the stock at a price of 1and sell it when Price is 9.

Note - You have to buy first and then you can sell. 

Let us proceed Toward to approach to solve one of the best problems of Data structure and algorithm.




This is a Dynamic programming problem it can easily be Solved by finding when the price of the stock is least and when is highest.
This is the easiest of all "Best Time to Buy and sell Stock" problems.

Best Time to Buy and sell stock  solution in C++


class Courpedia {
public:
    int maxProfit(vector<int>& prices) {
        int l=prices.size();
        int maximum[l];
        maximum[l-1]=prices[l-1];
        for(int i=l-2;i>=0;i--)
        {
  maximum[i]=max(prices[i],maximum[i+1]);
        }
       int max=0;
        for(int i=0;i<l;i++)
        {
        max=max(maximum[i]-prices[i],max);
        }
        return max;
        
        
    }
};




Best Time to Buy and Sell Stock in Java


class Courpedia {
public int maxProfit(int[] prices) {
int min=prices[0];
int max=0;
for(int i=0;i<prices.length;i++)
 {
min=Math.min(min,prices[i]);
max=Math.max(max,prices[i]-min);            
        }
 return max;
    }
}




Best Time to Buy and Sell Stock in Python

#shortest in Python
class Solution:
    def maxProfit(selfprices: List[int]) -> int:
        m=0, max_p=0
        for p in prices:
            if p < m: m = p
            if p - m > max_p: max_p = p - m
        return max_p




Now let us discuss the Time complexity of this code :

Time complexity : O(n)O(n). 

Space complexity: O(1)O(1). 
so this is the most efficient solution for the buy and sells stock question. There are a variety of questions you can get on leetcode,hackerrank, and CodeChef on this topic 

Practice this on leetcode.
Practice this on geeks for geeks.



:- You May Like:-