Bloomberg LP Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
in Scala:
object MaxProfitSingleBuy {
def main(args: Array[String]): Unit = {
val a = Array(100, 120, 150, 180, 200, 40, 56, 90, 280)
println(getMaxProfitSingleBuy(a))
}
def getMaxProfitSingleBuy(a:Array[Int]) : Int = {
var i = 0
var j = 0
var max = -1
var maxI = -1
var maxJ = -1
while (i < a.length - 1) {
while (i < a.length-1 && a(i) > a(i + 1)) i += 1
j = i + 1
while (j < a.length-1 && a(j) < a(j + 1)) j += 1
// found local maxima
if (a(j) - a(i) > max) {
max = a(j) - a(i)
maxI = i
maxJ = j
}
i += 1
}
return max
}
}
double maxProfit(std::vector<double> & prices)
{
double minSoFar = std::numeric_limits<double>::max();
double maxProfit = 0;
for( auto const& price: prices)
{
double CurrentMaxProfit = price - minSoFar;
maxProfit = std::max(CurrentMaxProfit, maxProfit);
minSoFar= std::min(price, minSoFar);
}
return maxProfit;
}
- Joe May 10, 2017