HomeSoftware DevelopmentMost distance between two even integers in a given array

# Most distance between two even integers in a given array

Given an array arr[] having N integers, the duty is to search out the utmost distance between any two occurrences of even integers.

Examples:

Enter: arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: 4
Clarification: The space between arr = 2 and arr = 6 is 4 which is the utmost distance between two even integers current within the given array.

Enter: arr[] = {3, 5, 6, 9, 11}
Output: 0
Clarification: The given array comprises lower than 2 even integers. Therefore, the utmost distance is 0.

Naive Method: The given downside could be solved by checking the space between all pairs of even integers occurring within the array and sustaining the utmost in them which would be the required reply.

Time Complexity: O(N2)
Auxiliary Area: O(1)

Environment friendly Method: This downside could be solved utilizing Two Pointer strategy.

• Deal with the case with lower than 2 even integers individually.
• The index of most distance even integers would be the index of the primary and the final incidence of even integers.
• This may be finished just by traversing the array utilizing two pointers – one from begin and one from finish.
• As quickly a fair integer is reached from each pointers, return the space between them.

Under is the implementation of the above strategy:

## C++

 `#embrace ` `utilizing` `namespace` `std;` ` `  `int` `maximizeDistance(``int` `arr[], ``int` `n)` `{` `    ` `    ` `    ``int` `i = 0;` ` `  `    ` `    ``whereas` `(i < n) {` `        ``if` `(arr[i] % 2 == 0) {` `            ``break``;` `        ``}` `        ``i++;` `    ``}` `    ` `    ` `    ``int` `j = n - 1;` ` `  `    ` `    ` `    ``whereas` `(j >= 0) {` `        ``if` `(arr[j] % 2 == 0) {` `            ``break``;` `        ``}` `        ``j--;` `    ``}` ` `  `    ` `    ` `    ``if` `(i >= j) {` `        ``return` `0;` `    ``}` ` `  `    ` `    ``return` `j - i;` `}` ` `  `int` `major()` `{` `    ``int` `arr[] = { 3, 4, 5, 6, 7, 8 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(``int``);` ` `  `    ``cout << maximizeDistance(arr, N);` ` `  `    ``return` `0;` `}`

Time Complexity: O(N)
Auxiliary Area: O(1)

RELATED ARTICLES