Find Maximum Length Sub-array with Specific Adjacent Differences

Given an array of integers ‘A’ of length ‘N’, find the maximum length of a sub-array where the absolute difference between adjacent elements is either 0 or 1.

Example:

Input:
A = [2, 4, 6, 7, 6, 9]
Output:
3
Explanation:

The sub-array [6, 7, 6] has adjacent elements with absolute differences of either 0 or 1, and its length is 3, which is the maximum possible.

Input:

T = number of test cases
For each test case:
N = number of elements in the array
Array A with N space-separated integers

Output:

For each test case, output the maximum length of the sub-array as a single integer in a new line.

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 104
  • -108 <= A[i] <= 108

Time limit: 1 sec.

Note:

No need to print the output; it is handled automatically. Implement the function to output the results.

AnswerBot
7d

Find the maximum length of a sub-array with adjacent differences of 0 or 1 in an array of integers.

  • Iterate through the array and keep track of the current sub-array length with adjacent differences of...read more

Omprakash Ray
21d
int tempSum = 0; int sum = 0; int[] arr = {2, 4, 6, 7, 6, 9, 5, 4, 3, 2}; for(int i = 0; i< arr.length-1; i++) { if(Math.abs(arr[i+1]-arr[i]) == 0 || Math.abs(arr[i+1]-arr[i]) == 1) { tempSum = tempSu...read more
Help your peers!
Add answer anonymously...
Visa Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter