1664. Number of schemes to generate balance numbers One question daily
1664. Number of schemes to generate balance numbers
Thought:
See when you read the question medium I know that it is definitely not really going to delete an element。Otherwise it will time out,So I tried to try polepythonFeature code:Use slice to process all data; But it's timeout。。
然后看官方answer,用的Dynamic planning。中心Thought是:
General nature,Now we will settle down i Delete elements, Obviously the bidding i The previous element bidding will not change from this,Bidding i The original was originally j,j>iThe array elements of the bid will move to the bidding j−1, Immediately bidding i The subsequent bidding elements will become the rated element, The even bidding element will become a strange number of bidding elements。
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
1545. 找出第 N 个二进制字符串中的第 K 位
LeetCode 1545. 找出第 N 个二进制字符串中的第 K 位 题解 — 递归与数学翻转解法,通过分析字符串构造规律(S₁=0,后续由前序+1+反转取反前序组成),将第 K 位分为左半、中间、右半三类递归求解,避免暴力生成导致内存溢出。适合准备面试、刷递归与位运算题型的算法学习者。
1825. Seek out MK average value
LeetCode 1825. 求出 MK 平均值 题解 — 使用三个 multiset 维护滑动窗口中的最小值、中间值和最大值集合,通过平衡插入与删除操作保持 lower 和 upper 各含 k 个元素,并实时维护 middle 的元素和以 O(log n) 计算剔除首尾 k 个后的平均值。适合准备系统设计面试或需要掌握有序集合与滑动窗口技巧的算法学习者。