[LeetCode] Ways to Make a Fair Array

1664. Ways to Make a Fair Array

You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.

For example, if nums = [6,1,7,4,1]:

  • Choosing to remove index 1 results in nums = [6,7,4,1].
  • Choosing to remove index 2 results in nums = [6,1,4,1].
  • Choosing to remove index 4 results in nums = [6,1,7,4].

An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.

Return the number of indices that you could choose such that after the removal, nums is fair.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int waysToMakeFair(vector<int>& nums) {
vector<pair<int, int>> psum{{0,0}};
for(int i = 0, odd = 0, even = 0; i < nums.size(); i++) {
if(i & 1) odd += nums[i];
else even += nums[i];
psum.push_back({odd,even});
}
int res = 0;
for(int i = 0; i < nums.size(); i++) {
auto [fo, fe] = psum[i];
auto [no, ne] = psum[i + 1];
auto [bo, be] = psum[nums.size()];
auto ce = bo - no;
auto co = be - ne;
if(fo + co == fe + ce)
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/04/PS/LeetCode/ways-to-make-a-fair-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.