Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Array element moved by k using single moves?
This problem involves simulating a badminton tournament where players compete until someone wins K consecutive matches. We have an array representing the queue of players, and we need to find who becomes the ultimate winner.
Syntax
int winner(int arr[], int n, int k);
Algorithm
The key insight is that we don't need to simulate every match. Instead, we can observe that −
- If K >= n-1, the largest element will always win
- Otherwise, we track the best player encountered and count consecutive wins
Begin
if k >= n-1, then return n
best_player := 0
win_count := 0
for each element e in arr, do
if e > best_player, then
best_player := e
if e is 0th element, then
win_count := 1
end if
else
increase win_count by 1
end if
if win_count >= k, then
return best player
done
return best player
End
Example
Let's implement the solution to find the winner of the badminton tournament −
#include <stdio.h>
int winner(int arr[], int n, int k) {
if (k >= n - 1) // if K exceeds the array size, then return n
return n;
int best_player = 0, win_count = 0; // initially best player and win count is not set
for (int i = 0; i < n; i++) { // for each member of the array
if (arr[i] > best_player) { // when arr[i] is better than the best one, update best
best_player = arr[i];
if (i) // if i is not the 0th element, set win_count as 1
win_count = 1;
} else // otherwise increase win count
win_count += 1;
if (win_count >= k) // if the win count is k or more than k, then we have got result
return best_player;
}
return best_player; // otherwise max element will be winner
}
int main() {
int arr[] = {3, 1, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
printf("Winner: %d<br>", winner(arr, n, k));
// Test with the example from problem description
int arr2[] = {2, 1, 3, 4, 5};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int k2 = 2;
printf("Winner: %d<br>", winner(arr2, n2, k2));
return 0;
}
Winner: 3 Winner: 5
How It Works
The algorithm works by tracking the strongest player encountered so far and counting consecutive wins. When a stronger player appears, they become the new best player and start their win streak. The simulation continues until someone achieves K consecutive wins.
Conclusion
This optimized approach avoids simulating every individual match by recognizing patterns in the tournament structure. It efficiently determines the winner in O(n) time complexity.
