Uber| Phone | Distinct Even Pair Sum

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2021-11-17Added By Anonymous
Source: Link

Company: Uber
Role: unknown
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

Given a circular array of N integers (i.e. A[0] and A[N - 1] are adjacent to each other), what's the maximum number of adjacent pairs that you can form whose sum are even? Note that each element can belong to at most one pair.
Can any one solve it efficiently in java?. I solved it in O(n) time but used two for loops and an extra array.

public int getDistinctPair(int[] nums){
  int len = nums.length;
  int count1=0,counter2=0;
  int[] a = new int[nums.length+2];
  for(int i=0;i<nums.length;i++){
    a[i]=nums[i-1];
  }
  int n = nums.length;
  a[n+1]=a[1];
  for(int i=1;i<=len-1;i++){
    if((a[i] & 1) == (a[i+1] & 1)){
      counter1++;
      i++;
    }
  }
  for(int i=2;i<=len;i++){
    if((a[i] & 1) == (a[i+1] & 1)){
      counter2++;
      i++;
    }
  }
  if(counter1>counter2)
    return counter1;
  return counter2;
}

Comments