Find All Unique Pairs of Maximum and Second Maximum Elements in Subarrays
The root of the problem is that a classmate asked about a lucky number problem: Codeforces 280B. Codeforces 281D is the same problem.
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
A lucky number is defined as the XOR value of the maximum and second maximum of a subarray. The task is to find the largest lucky number among all lucky numbers.
The brute force solution enumerates all subarrays, with time complexity O(N ^ 2).
Is there a better method?
That is the problem to discuss today.
General Solution: Fast Algorithm for Finding Maximum and Second-Maximum Pairs
There is actually a fast algorithm for finding the maximum and second maximum in subarrays:
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
It is based on this observation: for each number in the array, if it wants to become the second maximum, it can only pair with the first number greater than it in front of it, or the first number greater than it after it.
We can maintain a monotonically decreasing stack. When adding a new number, to maintain monotonicity we pop all numbers smaller than it. At this time, the new number is the first number after the popped numbers that is greater than them; the largest number on the stack top is the first number before the new number that is greater than it.
Time complexity: O(N),
space complexity: O(N).
1 |
|
The Solution I Thought of Independently
My solution uses the property of XOR. If we replaced XOR with another operation, it would not be general.
First traverse once to find the highest bit.
Then traverse again to find the numbers whose highest bit is 1. Let us call them the highest numbers.
Starting from these highest numbers, expand to both sides until encountering another highest number. During this process, find the second maximum and update the maximum lucky number. It can be proven that each number is visited at most twice.
Therefore, the total time complexity is O(N), and the space complexity is O(N).
1 |
|