Maximum Equal Adjacent Pairs After at Most One Replacement Problem
Description
LeetCode Problem 4066.
You are given a 1-indexed integer array nums.
You can choose two distinct values x and y and perform the following operation at most once:
- Replace every occurrence of
xinnumswithy.
Return the maximum possible number of pairs of adjacent elements that are equal after performing the operation.
Example 1:
Input: nums = [1,2,3,2]
Output: 2
Explanation:
- One optimal solution is to choose x = 3 and y = 2.
- The resulting array is [1, 2, 2, 2].
- There are 2 pairs of adjacent elements that are equal: (nums[2], nums[3]) and (nums[3], nums[4]).
- Therefore, the answer is 2.
Example 2:
Input: nums = [1,2,1,2,1]
Output: 4
Explanation:
- One optimal solution is to choose x = 1 and y = 2.
- The resulting array is [2, 2, 2, 2, 2].
- There are 4 pairs of adjacent elements that are equal: (nums[1], nums[2]), (nums[2], nums[3]), (nums[3], nums[4]), and (nums[4], nums[5]).
- Therefore, the answer is 4.
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation:
- One optimal solution is to perform no operation.
- Thus, the resulting array is [1, 1, 1].
- There are 2 pairs of adjacent elements that are equal: (nums[1], nums[2]) and (nums[2], nums[3]).
- Therefore, the answer is 2.
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Hash Map
Adjacent pairs that are already equal stay equal after any replacement: if both hold x they both become y. Count them as ans.
A replacement of x by y can only create new equal pairs from adjacent pairs that are exactly (x, y) or (y, x). So for every unequal adjacent pair, put the smaller value first and count how many times each unordered pair occurs. The best replacement is the pair that occurs most often, with count mx; doing nothing corresponds to mx = 0.
The answer is ans + mx. The pair can be encoded as a single 64-bit key such as small * 2^30 + large, since values are at most 10^9 < 2^30.
Complexity: O(n) time and O(n) extra space.
from collections import defaultdict
class Solution:
def maxEqualAdjacentPairs(self, nums: List[int]) -> int:
cnt = defaultdict(int)
ans = mx = 0
for x, y in zip(nums, nums[1:]):
if x == y:
ans += 1
else:
if x > y:
x, y = y, x
key = x << 30 | y
cnt[key] += 1
mx = max(mx, cnt[key])
ans += mx
return ans