Maximizing profit for given stock quotes

后端 未结 9 1900
無奈伤痛
無奈伤痛 2020-12-07 09:45

I was asked this question while interviewing for a startup and saw this again in the recent contest at

Code Sprint:systems

**The question :

You are

相关标签:
9条回答
  • 2020-12-07 10:40

    My reasoning is, you make profit for every stock bought before the maximum stock price. Using this line of thought, you buy every stock before the maximum price, sell it at the maximum, and repeat the same thing for the remaining stock prices.

    function profit(prices){
        var totalStocks = 0, profitMade = 0;
    
        var buySell = function(sortedPrices){
            for(var i = 0, len = sortedPrices.length; i < len; i++){
                if (i < len - 1){
                    totalStocks++;
                    profitMade = profitMade - sortedPrices[i];
                }else{
                    profitMade = profitMade + totalStocks * sortedPrices[i];
                    totalStocks = 0;
                }
            }
        }, splitMaxPrice = function(rawPrices){
            var leftStocks = rawPrices.splice(rawPrices.lastIndexOf(Math.max.apply(null, rawPrices))+1);
            buySell(rawPrices);
            if(leftStocks.length > 0){
                splitMaxPrice(leftStocks);
            }
            return;
        };
    
        splitMaxPrice(prices);
    
        return profitMade;
    
    }
    
    0 讨论(0)
  • 2020-12-07 10:42

    I just solved that problem in a contest site. I think I got a simpler algorithm than the accepted answer.

    1. smax = maximum stock price from the list
    2. then find the profit by assuming you have bought all the stocks till smax 
       and you sell it at the price of smax
    3. then check if smax is the last element of the stock price list 
       if yes then return profit as answer, 
       if no 
       then make a new list containing stock prices after smax to the last stock price
       and repeat steps 1-3 and keep adding profit of each iteration to get the final profit.
    
    0 讨论(0)
  • 2020-12-07 10:43

    your logic is correct...

    sell at global maxima's..but recursion is not required...

    if ith element is global maxima...sell all stocks before i!

    Now problem reduces to previous answer+ i+1 to N...

    recursion is not required...linearly we can calculate!

    0 讨论(0)
提交回复
热议问题