Created
September 8, 2022 19:45
-
-
Save AsifITk/1efa90144a4f456449e4f60bf07e41f8 to your computer and use it in GitHub Desktop.
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
let winner = (arr, k) => { | |
if (k >= arr.length) { | |
return Math.max(...arr); | |
} | |
let tem = {}; | |
let num1 = arr[0]; | |
let num2 = undefined; | |
for (let i = 1; i < arr.length; i++) { | |
num2 = arr[i]; | |
if (num1 > num2) { | |
tem[num1] = (tem[num1] || 0) + 1; | |
if (tem[num1] >= k) { | |
return num1; | |
} | |
} | |
else if (num1 < num2) { | |
tem[num2] = (tem[num2] || 0) + 1; | |
if (tem[num2] >= k) { | |
return num2; | |
} | |
num1 = num2; | |
} | |
} | |
return Math.max(...arr); | |
}; | |
let arr = [2, 1, 3, 5, 4, 6, 7], k = 2; | |
console.log(winner(arr, k)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment