Picking Numbers : HackerRank Solution in Python

Shounak Lohokare
2 min readJan 8, 2021

Solution in Python 3

from collections import Counterdef pickingNumbers(a):
countNums = Counter(a)
maxnum=0
for i in range(1, 100):
maxnum = max(maxnum, countNums[i]+countNums[i+1])

return maxnum

Explanation

We will import Counter from Python’s collections module. A Counter is a container that stores elements as dictionary keys and their counts or occurrences in a data structure as dictionary values.

We will pass a to the Counter

countNums = Counter(a)

countNums will contain count of each element in a. If a = [4, 6, 5, 3, 3, 1] then Counter(a) will be Counter({4: 1, 6: 1, 5: 1, 3: 2, 1: 1}).

Then we will declare a variable maxnum and initialize it to 0.

maxnum=0

Then we will use a for loop and iterate over range(1, 100) using a variable i.

for i in range(1, 100):

We will iterate from 1 till 99, (range function iterates up to but not including the upper limit which is 100).

Inside this for loop, we will use a max function and pass maxnum and countNums[i]+countNums[i+1] as parameters and return the value of function to maxnum itself.

maxnum = max(maxnum, countNums[i]+countNums[i+1])

countNums[i]+countNums[i+1] represents the sum of counts of numbers whose absolute difference is 1.

Thus as the above statement is in a for loop, the above statement is executed while the value is greater than equal to 1 and less than 100 (which are our constraints).

for i in range(1, 100):
maxnum = max(maxnum, countNums[i]+countNums[i+1])

At the end we return maxnum.

return maxnum

--

--

Shounak Lohokare

pretending to teach is one of the best way to learn.