Picking Numbers [Hacker Rank]

Kim Hayeon·2023년 5월 8일
0

Algorithm Study

목록 보기
15/37
post-thumbnail

Question

Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to 1.

Example

There are two subarrays meeting the criterion: [1, 1, 2, 2] and [4, 4, 5, 5, 5]. The maximum length subarray has 5 elements.

Function Description

Complete the pickingNumbers function in the editor below.

pickingNumbers has the following parameter(s):

  • int a[n]: an array of integers

Returns

  • int: the length of the longest subarray that meets the criterion

Input Format

The first line contains a single integer n, the size of the array a .
The second line contains n space-separated integers, each an a[i].

Constraints

  • 2 <= n <= 100
  • 0 < a[i] < 100
  • The answer will be >= 2.

Code


def pickingNumbers(a):
    # Write your code here
    answer = 0
    a = sorted(a)
    # [1, 3, 3, 4, 5, 6]
    for i in range(len(a)-1): # fix one element
        arr = [a[i]] # to save subarray
        for j in range(i+1, len(a)):
            if a[j] - a[i] <= 1: # defference is less than or equal to 1
                arr.append(a[j])
        answer = max(answer, len(arr))
        # print(arr)
        arr = [] # initialize arr
    return answer
                
profile
우리는 무엇이든 될 수 있어

0개의 댓글