LeetCode #1664: Ways to Make a Fair Array

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;     
    }
}

This seems simple but initially I went down wrong path, trying to use way too many arrays. I gave up and looked at https://leetcode.com/problems/ways-to-make-a-fair-array/discuss/944567/Java-O(N)-and-constant-space-beats-100-easy-solution. My solution is basically transpilation of it in PHP.

Ref: https://leetcode.com/problems/ways-to-make-a-fair-array/

Leave a Reply

Your email address will not be published. Required fields are marked *