Final Element After Subarray Deletions Problem
Description
LeetCode Problem 3828.
You are given an integer array nums.
Two players, Alice and Bob, play a game in turns, with Alice playing first.
- In each turn, the current player chooses any subarray
nums[l..r]such thatr - l + 1 < m, wheremis the current length of the array. - The selected subarray is removed, and the remaining elements are concatenated to form the new array.
- The game continues until only one element remains.
Alice aims to maximize the final element, while Bob aims to minimize it. Assuming both play optimally, return the value of the final remaining element.
Example 1:
Input: nums = [1,5,2]
Output: 2
Explanation:
One valid optimal strategy:
- Alice removes [1], array becomes [5, 2].
- Bob removes [5], array becomes [2]. Thus, the answer is 2.
Example 2:
Input: nums = [3,7]
Output: 7
Explanation:
Alice removes [3], leaving the array [7]. Since Bob cannot play a turn now, the answer is 7.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Brain Teaser
Alice moves first and may delete everything between the first and last elements in one move (that subarray is shorter than the whole array), leaving exactly two elements, so she can force the result to be at least max(nums[0], nums[n - 1]). (If the array has one element there is no game, and the formula still holds.)
For any middle element, Bob can always remove it when it is his turn to choose, so Alice cannot do better than the larger end. Hence the answer is exactly max(nums[0], nums[n - 1]).
Complexity: O(1) time and O(1) space.
class Solution:
def finalElement(self, nums: List[int]) -> int:
return max(nums[0], nums[-1])