jsasitorn
BAN USER
Comments (2)
Reputation 20
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 vote
This question was a little hard to read. The question does say the stock is sold n days after the stocks is purchased. So you need to keep track of a running max that is price[today] - price[n days later]
Here is a solution in php:
$prices = array(20,50,52,10,45,34, 100);
function getMaxProfit($prices, $n) {
$maxProfit = 0; //assume there is a profitable day possible
$bestDay = 0;
for ($i=0; $i < (sizeof($prices) - $n); $i++) {
$todayProfit = $prices[$i+$n] - $prices[$i];
echo $todayProfit . PHP_EOL;
if ($todayProfit > $maxProfit) {
$maxProfit = $todayProfit;
$bestDay = $i;
}
}
return $bestDay + 1; //days should start with 1
}
echo getMaxProfit($prices, 3);
Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
Assuming the elements are unique, you can do nested for loops to ensure less than the normal 2^n runtime seen when generating all possible subsets.
- jsasitorn April 01, 2013