Problem · Array

Maximum Even-Sum Neighboring Pairs

Learn this problem
MediumDRWOA

Problem statement

You are given N numbers on a circle, described by an integer array A. A neighboring pair is formed by two adjacent positions on the circle. This means positions i and i + 1 are neighbors, and the last position is also a neighbor of the first position.

Your task is to find the maximum number of neighboring pairs whose sums are even. Each array element can belong to at most one chosen pair.

Function

solution(A: int[]) → int

Examples

Example 1

A = [4,2,5,8,7,3,7]return = 2

One optimal choice is (A[0], A[1]) and (A[4], A[5]). Another optimal choice is (A[0], A[1]) and (A[5], A[6]).

  • Choice 1: 4, 2, 5, 8, 7, 3, 7
  • Choice 2: 4, 2, 5, 8, 7, 3, 7

Example 2

A = [14,21,16,35,22]return = 1

The only qualifying neighboring pair is (A[0], A[4]), using the circular adjacency between the first and last elements.

Circular pair: 14, 21, 16, 35, 22

Example 3

A = [5,5,5,5,5,5]return = 3

All neighboring sums are even. We can create three non-overlapping pairs, for example (A[0], A[5]), (A[1], A[2]), and (A[3], A[4]).

More DRW problems

drafts saved locally
public int solution(int[] A) {
  // write your code here
}
A[4,2,5,8,7,3,7]
expected2
checking account