Maximizing profit for given stock quotes

后端 未结 9 1915
無奈伤痛
無奈伤痛 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;
    
    }
    

提交回复
热议问题