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
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;
}
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.
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!