🪴 Hayul's digital garden

Search

Search IconIcon to open search

Picking Numbers

Last updated Jan 10, 2023 Edit Source

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

a = [1,1,2,2,4,4,5,5,5]

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): 

Returns

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 a[i] .

Constraints

Sample Input 0

1
2
6
4 6 5 3 3 1

Sample Output 0

3

Explanation 0

We choose the following multiset of integers from the array: {4,3,3}. Each pair in the multiset has an absolute difference  <= 1(i.e., |4-1| = 1 and |3-3| = 0), so we print the number of chosen integers, 3, as our answer.

# 나의 풀이

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import math
import os
import random
import re
import sys
from collections import Counter

def pickingNumbers(a):
   
 # imput is un array of numbers.
    count_nums = Counter(a)
    max_num = 0
    
    for i in range(1, 100):

        max_num = max(max_num, 
				  count_nums[i] + count_nums[i+1])
    return max_num

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
    n = int(input().strip())
    a = list(map(int, input().rstrip().split()))
    
    result = pickingNumbers(a)
    
    fptr.write(str(result) + '\n')
    fptr.close()

Note

이 문제는 Counter()로 일단 세고 시작하면 간단한다. 개수를 센 이후에는 양 옆의 크기를 더한 것이 가장 큰 경우가 답이므로.