LeetCode 1664: Ways to Make a Fair Array

May. 8, 2021

I tried to do this all by myself but got stuck, ended up transpiling this solution in PHP.

class Solution {

  /**
    * @param Integer[] $nums
    * @return Integer
    */
    function waysToMakeFair($nums) {
        $len = count($nums);
        $ans = 0;

        $leftOdd = 0;
        $rightOdd = 0;
        $leftEven = 0;
        $rightEven = 0;

        for ($i=0; $i<$len; $i++) {
            if ($i%2 === 0)
                $rightEven += $nums[$i];
            else
                $rightOdd += $nums[$i];
        }

        for ($i=0; $i<$len; $i++) {
            if ($i%2 === 0)
                $rightEven -= $nums[$i];
            else
                $rightOdd -= $nums[$i];

            if ($leftEven + $rightOdd === $rightEven + $leftOdd) $ans++;

            if ($i%2 === 0)
                $leftEven += $nums[$i];
            else
                $leftOdd += $nums[$i];
        }

        return $ans;
    }
}