1664. Ways to Make a Fair Array — Daily Problem
1664. Ways to Make a Fair Array
Approach
When reading the problem, I immediately knew we shouldn't actually delete elements one by one — that would time out. So I tried a "pure Python" approach using slices to process all the data, but it still timed out.
Then I checked the official solution, which uses dynamic programming. The key insight is:
In general, suppose we delete element at index
i. Obviously, elements before indexiremain unchanged. Elements originally at indexjwherej > ishift to indexj − 1. Therefore, elements after indexithat were at even indices become odd, and vice versa.
Code
class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
flag = 0
for i in range(len(nums)):
temp_nums = nums[:i] + nums[i+1:]
if sum(temp_nums[::2])==sum(temp_nums[1::2]):
flag += 1
return flagclass Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
res = odd1 = even1 = odd2 = even2 = 0
for i, num in enumerate(nums):
if i & 1:
odd2 += num
else:
even2 += num
for i, num in enumerate(nums):
if i & 1:
odd2 -= num
else:
even2 -= num
if odd1 + even2 == odd2 + even1:
res += 1
if i & 1:
odd1 += num
else:
even1 += num
return res贡献者
这篇文章有帮助吗?
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0