Similar Problems

Similar Problems not available

Find The Winner Of An Array Game - Leetcode Solution

Companies:

LeetCode:  Find The Winner Of An Array Game Leetcode Solution

Difficulty: Medium

Topics: array simulation  

Problem statement

You are given an integer array nums, where the elements can be rearranged. You need to find the maximum possible score of the array.

The score of an array is defined as follows:

The score is the number of elements on one side of the array that are strictly larger than the other side of the array.

Return the maximum possible score of the array.

Solution

To solve this problem, we can sort the array in decreasing order and initialize two pointers, left and right, to the beginning and end of the array respectively. We then loop through the array and move the pointer towards the center, increasing the score for each comparison between elements. We keep track of the maximum score seen so far and return it at the end.

Here is the implementation of the above-mentioned idea:

class Solution:
    def maxScore(self, nums: List[int]) -> int:
        nums.sort(reverse=True) # Sort the array in descending order
        left, right = 0, len(nums) - 1 # Initialize two pointers
        max_score = 0 # Initialize the maximum score

        while left < right: # Loop through the array
            if nums[left] > nums[right]: # Left pointer is larger than right pointer
                max_score += 1
                left += 1
            else: # Right pointer is larger than left pointer
                max_score += 1
                right -= 1

        return max_score

The time complexity of this solution is O(n log n) due to the sorting operation, and the space complexity is O(1) as we are using constant amount of extra space.

Find The Winner Of An Array Game Solution Code

1