Skip to content

Instantly share code, notes, and snippets.

@blacksheep557
Created August 24, 2021 06:12
Show Gist options
  • Select an option

  • Save blacksheep557/3e749e19ad3620a3b29f449c65ff71ed to your computer and use it in GitHub Desktop.

Select an option

Save blacksheep557/3e749e19ad3620a3b29f449c65ff71ed to your computer and use it in GitHub Desktop.
function getMaxProfit(array) {
let profit = 0;
for (let i = 0; i < array.length; i++) {
let max = array[i]
for (let j = i + 1; j < array.length; j++) {
if (max < array[j]) max = array[j]
}
profit += max - array[i]
}
return profit
}
// console.log(getMaxProfit([1, 2, 3, 4, 5, 6]))// => 15 (Since we are allowed to buy everyday one stock we will buy at price 1, 2, 3, 4, 5 and since we can sell all the stocks at once so we will sell when the value becomes 6. So the total profit will be (6 - 1) + (6 - 2) + (6 - 3) + (6 - 4) + (6 - 5) i.e 15
// console.log(getMaxProfit([6, 5, 4, 3, 2, 1]))// => 0 (nothing to buy as we will not be able to make profit)
// console.log(getMaxProfit([1, 6, 5, 10, 8, 7]))// => 18 (buy at 1,6,5 and sell all at 10)
// console.log(getMaxProfit([1, 2, 10, 3, 2, 7, 3, 2]))// => 26 (buy at 1,2 and sell them at 10. Then buy at 3,2 and sell them at 7)
function uniqueVals(object) {
const charMap = {};
for (let key of Object.keys(object).reverse()) {
for (let i = 0; i < object[key].length; i++) {
if (charMap[object[key][i]]) {
object[key].splice(i, 1)
i--
}
else
charMap[object[key][i]] = 1
}
}
return object
}
console.log(uniqueVals({
"1": ["A", "B", "C"],
"2": ["A", "B", "D", "A"],
}))
console.log(uniqueVals({
"1": ["C", "F", "G"],
"2": ["A", "B", "C"],
"3": ["A", "B", "D"],
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment