Program to find the winner of an array game using Python


Suppose we have an array called arr, this contains unique elements and we also have another value k. Now consider a game where we take first two elements of the array. In each turn, we compare arr[0] with arr[1], and the larger value wins and remains at position 0 and the smaller value moves to the end of the array. This game will end when a value wins’ k consecutive rounds. We have to find the winner from the array.

So, if the input is like arr = [1,5,6,3,4,2], and k = 3, then the output will be 6 because

  • round 1, arr = [1,5,6,3,4,2], winner 5, win count for 5 is 1

  • round 2, arr = [5,6,3,4,2,1], winner 6, win count for 6 is 1

  • round 3, arr = [6,3,4,2,1,5], winner 6, win count for 6 is 2

  • round 3, arr = [6,4,2,1,5,3], winner 6, win count for 6 is 3

So winner is 6 as it won three times (k = 3)

To solve this, we will follow these steps −

  • l := size of arr

  • prev := arr[0]

  • count := 0

  • for i in range 1 to l - 1, do

    • if prev > arr[i], then

      • count := count + 1

    • otherwise,

      • prev := arr[i]

      • count := 1

    • if count is same as k, then

      • return prev

  • return prev

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(arr, k):
   l = len(arr)
   prev = arr[0]
   count = 0
   for i in range(1, l):
      if prev > arr[i]:
         count+=1
      else:
         prev = arr[i]
         count = 1
      if count == k:
         return prev
   return prev
arr = [1,5,6,3,4,2]
k = 3
print(solve(arr, k))

Input

[1,5,6,3,4,2], 3

Output

6

Updated on: 29-May-2021

847 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements