This Python program is designed to solve a problem of finding the longest subarray in a given array where the absolute difference between any two elements is less than or equal to 1. The function 'longestSubarray' accepts an array as a parameter and returns the length of the longest subarray that meets the condition.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution works by iterating over the array and for each element, it starts a new subarray. It keeps adding elements to the subarray as long as the absolute difference between any two elements in the subarray is less than or equal to 1. If it encounters an element that would make the difference greater than 1, it breaks the loop and starts a new subarray from the next element. The length of the longest subarray found is kept track of and returned as the result.
import math
import os
import random
import re
import sys
def longestSubarray(arr):
n = len(arr)
ans = 0
for i in range(n):
w = []
cnt = 0
for j in range(i, n):
if arr[j] in w:
cnt += 1
continue
if len(w) == 0:
w.append(arr[j])
elif len(w) == 1:
if abs(w[0] - arr[j]) > 1:
break
else:
w.append(arr[j])
else:
break
cnt += 1
ans = max(ans, cnt)
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
result = longestSubarray(arr)
fptr.write(str(result) + '
')
fptr.close()
If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.