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 ___isfair. _
Input: nums =[2,1,6,4]Output: 1Explanation:
Remove index 0:[1,6,4]-> Even sum:1+4=5. Odd sum:6. Not fair.Remove index 1:[2,6,4]-> Even sum:2+4=6. Odd sum:6. Fair.Remove index 2:[2,1,4]-> Even sum:2+4=6. Odd sum:1. Not fair.Remove index 3:[2,1,6]-> Even sum:2+6=8. Odd sum:1. Not fair.There is1 index that you can remove to make nums fair.
When removing an element, the parity (even/odd) of indices after it flips. We can precompute prefix sums for even and odd indices, and for each removal, calculate the new even and odd sums efficiently.
classSolution {
publicintwaysToMakeFair(int[] nums) {
int n = nums.length;
int[] even =newint[n+1], odd =newint[n+1];
for (int i = 0; i < n; i++) {
even[i+1]= even[i];
odd[i+1]= odd[i];
if (i % 2 == 0) even[i+1]+= nums[i];
else odd[i+1]+= nums[i];
}
int ans = 0;
for (int i = 0; i < n; i++) {
int evenSum = even[i]+ odd[n]- odd[i+1];
int oddSum = odd[i]+ even[n]- even[i+1];
if (evenSum == oddSum) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funwaysToMakeFair(nums: IntArray): Int {
val n = nums.size
val even = IntArray(n+1)
val odd = IntArray(n+1)
for (i in0 until n) {
even[i+1] = even[i]
odd[i+1] = odd[i]
if (i % 2==0) even[i+1] += nums[i] else odd[i+1] += nums[i]
}
var ans = 0for (i in0 until n) {
val evenSum = even[i] + odd[n] - odd[i+1]
val oddSum = odd[i] + even[n] - even[i+1]
if (evenSum == oddSum) ans++ }
return ans
}
}
from typing import List
classSolution:
defwaysToMakeFair(self, nums: List[int]) -> int:
n = len(nums)
even = [0]*(n+1)
odd = [0]*(n+1)
for i in range(n):
even[i+1] = even[i]
odd[i+1] = odd[i]
if i %2==0:
even[i+1] += nums[i]
else:
odd[i+1] += nums[i]
ans =0for i in range(n):
evenSum = even[i] + odd[n] - odd[i+1]
oddSum = odd[i] + even[n] - even[i+1]
if evenSum == oddSum:
ans +=1return ans