Skip to content

Commit 3cff939

Browse files
committed
chore: add daily leetcode post 1664生成平衡数组的方案数_translated
1 parent 9f8daff commit 3cff939

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
title: 1664. Number of schemes to generate balance numbers One question daily
3+
date: '2024.01.01 0:00'
4+
tags:
5+
- - Python
6+
- - answer
7+
- - Dynamic planning
8+
- - One question daily
9+
abbrlink: 1978f474
10+
---
11+
12+
[1664. Number of schemes to generate balance numbers](https://leetcode.cn/problems/ways-to-make-a-fair-array/description/?orderBy=most_relevant)
13+
14+
# Thought:
15+
16+
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;
17+
But it's timeout。。
18+
19+
然后看官方answer,用的Dynamic planning。中心Thought是:
20+
>General nature,Now we will settle down i Delete elements,
21+
Obviously the bidding i The previous element bidding will not change from this,Bidding i
22+
The original was originally j,j>iThe array elements of the bid will move to the bidding j−1,
23+
Immediately bidding i The subsequent bidding elements will become the rated element,
24+
The even bidding element will become a strange number of bidding elements。
25+
26+
# Code
27+
28+
```python slice
29+
class Solution:
30+
def waysToMakeFair(self, nums: List[int]) -> int:
31+
flag = 0
32+
for i in range(len(nums)):
33+
temp_nums = nums[:i] + nums[i+1:]
34+
if sum(temp_nums[::2])==sum(temp_nums[1::2]):
35+
flag += 1
36+
return flag
37+
```
38+
39+
40+
41+
```python 官方answer
42+
class Solution:
43+
def waysToMakeFair(self, nums: List[int]) -> int:
44+
res = odd1 = even1 = odd2 = even2 = 0
45+
for i, num in enumerate(nums):
46+
if i & 1:
47+
odd2 += num
48+
else:
49+
even2 += num
50+
for i, num in enumerate(nums):
51+
if i & 1:
52+
odd2 -= num
53+
else:
54+
even2 -= num
55+
if odd1 + even2 == odd2 + even1:
56+
res += 1
57+
if i & 1:
58+
odd1 += num
59+
else:
60+
even1 += num
61+
return res
62+
```
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+

0 commit comments

Comments
 (0)