Created
August 2, 2019 04:35
-
-
Save wataruoguchi/a8ad9d621e388b014f5fa25656191352 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
// https://practice.geeksforgeeks.org/problems/stock-span-problem/0 | |
function stockSpan(arr) { | |
let idx; | |
let len = arr.length; | |
let resArr = new Array(arr.length); | |
// It's always 1 because nothing is before this. | |
resArr[0] = 1; | |
for (idx = 1; idx < len; idx++) { | |
resArr[idx] = 1; | |
// Traverse left while the next element on left is smaller | |
let idxJ = idx - 1; | |
while (idxJ >= 0 && arr[idx] >= arr[idxJ]) { | |
// idxJ goes to left | |
resArr[idx] += 1; | |
idxJ -= 1; | |
} | |
} | |
return resArr; | |
} | |
const arrEx1 = [100, 80, 60, 70, 60, 75, 85]; | |
const resEx1 = stockSpan(arrEx1); | |
console.log(resEx1.join(',') === '1,1,1,2,1,4,6'); | |
const arrEx2 = [10, 4, 5, 90, 120, 80]; | |
const resEx2 = stockSpan(arrEx2); | |
console.log(resEx2.join(',') === '1,1,2,4,5,1'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment