---
# System prepended metadata

title: 1664. Ways to Make a Fair Array
tags: [Leetcode, Three Pass, Medium, Greedy]

---

# 1664. Ways to Make a Fair Array
###### tags: `Leetcode` `Medium` `Greedy` `Three Pass`
Link: https://leetcode.com/problems/ways-to-make-a-fair-array/description/
## 思路
需要记下来每个位置左边(不包含自己)和右边(不包含自己)所有even indices和odd indices数字之和
如果```leftEven[i]+rightOdd[i]==leftOdd[i]+rightEven[i]```就说明是一个fair array
## Code
```java=
class Solution {
    public int waysToMakeFair(int[] nums) {
        int n = nums.length;
        int[] leftEven = new int[n];
        int[] leftOdd = new int[n];
        int even = 0, odd = 0;
        for(int i=0; i<n; i++){
            leftEven[i] = even;
            leftOdd[i] = odd;
            if((i-1)%2==0) even += nums[i];
            else odd += nums[i];
        }
        int[] rightEven = new int[n];
        int[] rightOdd = new int[n];
        even = 0;
        odd = 0;
        for(int i=n-1; i>=0; i--){
            rightEven[i] = even;
            rightOdd[i] = odd;
            if((i-1)%2==0) even += nums[i];
            else odd += nums[i];
        }
        int ans = 0;
        for(int i=0; i<n; i++){
            if(leftEven[i]+rightOdd[i]==leftOdd[i]+rightEven[i]) ans++;
        }
        return ans;
    }
}
```