Created
April 15, 2019 12:57
-
-
Save stevemu/15fe662ef1686dde3bce3c74c2977328 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
// algorithm question | |
// how to solve the buy - sell problem | |
// q: [3,5,6,9,2] | |
// a: 6 | |
// init best dff = 3-5 | |
// for each number in array | |
// loop each number after the number | |
// if firstNum > secondNum, skip | |
// cal the diff | |
// if diff bigger than bestDiff, replace it | |
// let arr = [3, 5, 6, 9, 2] // 6 | |
// let arr = [10,7,3,2] // -1 | |
// let arr = [2,12,5,16,4,3,7] // 14 | |
let arr = [100,34,3,2,10,3] // 8 | |
let diffArr = [] | |
// let bestDiff = 0 | |
for (let i = 0; i < arr.length - 1; i++) { | |
let currentNumber = arr[i] | |
for (let j = i + 1; j < arr.length; j++) { | |
let nextNumber = arr[j] | |
let diff = nextNumber - currentNumber | |
diffArr.push(diff) | |
// console.log(diff); | |
// if (currentNumber < nextNumber) { | |
// diff = diff * -1 | |
// console.log(diff); | |
// console.log(diff); | |
// if (diff > bestDiff) { | |
// bestDiff = diff | |
// } | |
// } | |
} | |
} | |
// console.log(diffArr); | |
let sortedArr = diffArr.sort((a, b) => { | |
if (a < b) { | |
return 1 | |
} | |
if (a > b) { | |
return -1 | |
} | |
return 0 | |
}) | |
console.log(sortedArr[0]); | |
// console.log(sortedArr[0]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment