Picking Numbers : HackerRank Solution in Python

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Delete Cookie in VBScript?

Software for Assets Management

A Basic Understanding of MVC

5 steps to setup Agile/Scrum in a 140-year bank

What is NPM? A Basic Introduction to Package Managers

Branches in Git Bash

CS371p Spring 2022 Week #3: Sumedh Kandadai

Find Missing Index: In-place

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shounak Lohokare

Shounak Lohokare

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

More from Medium

Python queries to work with multiple instances of Oracle and SQL Server.

LightGBM Starter Code

VS Code(1.66.2) Setting Up python interpreter path

LC 53 / maxSubArray (easy)