A Subarray is an array taken from a original array between any two indices L and R where and N is the Size of the given array.
Now you are given an array having N elements and your task is to find the count of all the subarrays whose product of its elements is Even.
Example:
Input: n=3, arr={2,3,4}
Output: 5
Approach
Java
public class OnlyEven {public static void main(String args[]) throws Exception {int n = 3;int cntod = 0;long res = n * (n + 1) / 2;int arr[] = { 2, 3, 4 };for (int i = 0; i < n; i++) {if ((arr[i] & 1) == 1) {cntod++;while (++i < n) {if ((arr[i] & 1) == 0)break;cntod++;}if (cntod == 1)res--;elseres -= (cntod * (cntod + 1)) / 2;cntod = 0;}}System.out.println(res);}}
No comments:
Post a Comment