If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example one: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.
Example two: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
My solution:
walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval. TimeComplexity is O(n) space complexity is O(1) only using one object.
const perfectPrice = (prices, peak = {
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable: {}
}) => {
const week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
prices.forEach((price, day, all) => {
if (peak['buy'] === null) {
peak['buy_day'] = day
peak['buy'] = price
} else if (price < peak['buy']) {
peak['buy'] = price
peak['buy_day'] = day
}
if (peak['profit'] < (price - peak['buy'])) {
peak.profitable = {
buy: week[peak.buy_day],
buy_at: peak['buy'],
sell: week[day],
sell_at: price,
profit: price - peak['buy']
}
peak['profit'] = price - peak['buy']
}
});
return ((peak || {}).profitable || {}).profit ? peak.profitable : 'not profitable to sell';
}
console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
[2, 9, 5, 3, 1, 4]
. It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day. \$\endgroup\$