LeetCode-in-Java

3917. Count Indices With Opposite Parity

Easy

You are given an integer array nums of length n.

The score of an index i is defined as the number of indices j such that:

Return an integer array answer of length n, where answer[i] is the score of index i.

Example 1:

Input: nums = [1,2,3,4]

Output: [2,1,1,0]

Explanation:

Thus, the answer = [2, 1, 1, 0].

Example 2:

Input: nums = [1]

Output: [0]

Explanation:

There is only one element in nums. Thus, the score of index 0 is 0.

Constraints:

Solution

public class Solution {
    public int[] countOppositeParity(int[] nums) {
        int n = nums.length;
        int odd = 0;
        int even = 0;
        int[] result = new int[n];
        for (int i = n - 1; i >= 0; i--) {
            if ((nums[i] & 1) == 1) {
                result[i] = even;
                odd++;
            } else {
                result[i] = odd;
                even++;
            }
        }
        return result;
    }
}