You are given an array A of N integers. If you make the array whole using the following operation, then what is the minimum number of operations required to make the entire array even?
Note: It can be proved that this is always possible.
Operation
Select an index and perform operation:
P=Ai+Ai+1; Q=Ai-Ai+1;
Ai=P; Ai+1=Q;
Example:
Input: n=4, a[]={1,3,2,2}
Output: 1
Approach
Java
public class MakeArrayEven {public static void main(String[] args) {int n = 4;int[] a = { 1, 3, 2, 2 };int ans = 0;for (int i = 0; i < n; i++) {// if evenif (a[i] % 2 == 0)continue;if (i == n - 1) {ans += 2;continue;}// if evenif (a[i + 1] % 2 == 0) {ans += 2;a[i + 1] = 2 * a[i + 1];} else {ans += 1;a[i + 1] = a[i] - a[i + 1];}}System.out.println(ans);}}
No comments:
Post a Comment