Created
May 19, 2017 02:35
-
-
Save fourcolors/84ade2786104dcb7725585c42aef822c to your computer and use it in GitHub Desktop.
Traditional Stock Buy Sell Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Problem: Transaction in k | |
* List the days to buy and days to sell | |
* Complexity | |
* p = prices | |
* k = transactions | |
* | |
* O(p + k) | |
*/ | |
const daysToSell = (prices, k) => { | |
const buySellDays = [] | |
let minMaxBool = true | |
let profit = 0 | |
// count how many transactions have been pushed | |
let i = 0; | |
prices.forEach((price, day) => { | |
if (prices.length - 1 === day) { | |
if (!minMaxBool) { | |
buySellDays[i].sellDay = day | |
buySellDays[i].localProfit = prices[day] - prices[buySellDays[i].buyDay] | |
profit = profit + prices[day] | |
} | |
// last day reached | |
return; | |
} | |
if (minMaxBool) { | |
// look for min | |
if (price < prices[day + 1]) { | |
buySellDays[i] = {'buyDay': day} | |
minMaxBool = false | |
profit = profit - prices[day] | |
} | |
} else { | |
if (price > prices[day + 1]) { | |
profit = profit + prices[day] | |
buySellDays[i].sellDay = day | |
buySellDays[i].localProfit = prices[day] - prices[buySellDays[i].buyDay] | |
i++ | |
minMaxBool = true | |
} | |
} | |
}) | |
buySellDays.sort((tranA, tranB) => { | |
return tranA.localProfit < tranB.localProfit | |
}) | |
const limitedTransactions = buySellDays.slice(0, k) | |
const limitedProfits = limitedTransactions.reduce((total, transaction) => { | |
return total + transaction.localProfit | |
}, 0) | |
return {'transactions': buySellDays.slice(0, k), 'totalProfit': limitedProfits} | |
} | |
const prices = [2, 5, 7, 1, 4, 3, 1, 3] | |
console.log(daysToSell(prices1, 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wouldn't use this. There is a bug in this. Doesn't work in this set of data
const prices = [2, 5, 7, 1, 4, 3, 2, 20]