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贡献者
Recent Updates
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
1653. Minimum Deletions to Make String Balanced
LeetCode 1653. Minimum Deletions to Make String Balanced — DP and stack-free counting with two passes, tracking 'a' and 'b' counts to minimize deletions for CS learners.
1664. 生成平衡数组的方案数
LeetCode 1664. 生成平衡数组的方案数 题解 — 使用动态规划与奇偶性分析,核心技巧是预处理前缀奇偶和与后缀奇偶和,在枚举删除每个元素时 O(1) 判断剩余数组奇偶下标和是否相等。适合准备算法面试、刷 LeetCode 中等题的求职者和 CS 学生。