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

Unity: Creating a spawn routine

DevOps for SAP Integration Suite (CPI) with ReleaseOwl

The Science of Project Planning - Part 1

Control Statements in Java

How the heck we forget performance?

Part 4: Lessons Learned and Key Takeaways

Linked Lists and How to Implement Them in Ruby

Break Your Software, or, How to Run a Gameday

skeleton typing at a computer

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

Generating SQL Aliases using Python (String Manipulation)

Useful functions in Python

Flying Tello EDU Drones in Python

CRUNCH COUNTER IN PYTHON