Best Time to Buy and Sell Stock


  • 0

    We need to find out the maximum difference (which will be the maximum profit) between two numbers in the given array. Also, the second number (selling price) must be larger than the first one (buying price).


    Click here to see the full article post


  • 0
    N

    has the first approach consider j>i?


  • 0

    Sorry, j should start with i+1. Thanks.


  • 0

    I am not sure why Zero is considered as the valid value is array for selling or buying stocks.Few of my test cases are failing because of this.For e.g. : [2,1,2,1,0,1,2]


  • 0

    mark :) I am here


  • 0
    A

    Is Approach #2 a dp approach?


  • 0
    B

    First time been here


  • 0
    H

    I really dont think the approach #2 is a DP approach...


  • 0
    S

    Approach 2: Greedy approach


  • 0
    J
    int maxProfit(int* prices, int pricesSize) {
        if (NULL == prices || pricesSize <= 0)
        	return  0;
        	
        int minPrice = prices[0];
        int max_profit = 0, i = 0;
    	
    	for(i = 1; i < pricesSize; i ++)
    	{
    		int tmpProfit = prices[i] - minPrice;
    
    		if (prices[i] < minPrice)
    		{
    			minPrice = prices[i];
    		}
    		
    		if ((max_profit < tmpProfit))
    		{
    			max_profit = tmpProfit;
    		}
    	}
    			
        return max_profit;
    }
    

  • 0
    R

    Slightly more simpler

    public int maxProfit(int[] prices) {
        int maxPrice = 0;
        int profit = 0;
        for (int i = prices.length - 1 ; i >= 0 ; i--) {
            profit = Math.max(maxPrice - prices[i], profit);
            maxPrice = Math.max(maxPrice, prices[i]);
        }
        return profit;
    }

  • 0
    N

    class Solution(object):
    def maxProfit(self, prices):

        sol = list()
        for index, value in enumerate(prices):
            starting=prices[:index+1]
            ending=prices[index+1:]
            if starting and ending:
                value = max(ending)-min(starting)
                sol.append(value)
        if sol:
            j=max(sol)
            if j>0:
                return (max(sol))
            else:
                return 0
        else:
            return 0

  • 0
    S

    Condition about selling and buying is not exactly clear. It means that you must buy as a first operation and only then sell? Correct?
    So, it means you don't have stocks before these operations, so you can't sell, then buy?


  • 1

    Why not just use Math.min/max?

    maxprofit = Math.max(maxprofit, prices[i] - minprice);
    minprice = Math.min(minprice, prices[i]);
    

  • 0

    I dont think the approach #2 is a DP approach


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.