Skip to content

Instantly share code, notes, and snippets.

@AsifITk
Created September 8, 2022 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AsifITk/1efa90144a4f456449e4f60bf07e41f8 to your computer and use it in GitHub Desktop.
Save AsifITk/1efa90144a4f456449e4f60bf07e41f8 to your computer and use it in GitHub Desktop.
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