Created
August 24, 2021 06:12
-
-
Save blacksheep557/3e749e19ad3620a3b29f449c65ff71ed to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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