Picking Numbers

It was a beautiful Sunday in the Twin Cities of Minneapolis and St. Paul. It snowed until around 07:00 AM and the sun came up. We received around 7 inches of fresh snow. The snow was wet and heavy. The branches of trees were holding the heavy fresh snow. Several people walked on the parkway taking pictures. The outside temperature went up to the high 20s. Since the sun was shining the inside temperature at home got up to 72F. It felt quite nice given that we keep our thermostat at 68F.

Received via email a message to give the Picking Numbers  HackerRank challenge a try. The idea is to provided a set of integers, figure out the maximum count of numbers that differ by one and return such value.

I used the following set to test my code written in Java:

9
1 1 2 2 4 4 5 5 5 

5

6
4 6 5 3 3 1

3

6
1 2 2 3 1 2

5

The pickingNumbers() function follows:

    public static int pickingNumbers(List<Integer> a) {

    	// **** empty or 1 item ****
    	if (a.size() <= 1) 
    		return 0;

    	// **** sort list in ascending order ****
    	Collections.sort(a);
//    	System.out.println("a: " + a.toString());
    	
    	// **** loop counting consecutive numbers whose value is <= 1 ****
    	int maxCount	= 0;
    	int count 		= 0;
    	int fi			= 0;
    	
    	for (int i = 1; i < a.size(); i++) {
    		
    		// **** count this entry (if needed) ****
    		if (Math.abs(a.get(fi) - a.get(i)) <= 1) { // **** increment the count **** if (count == 0) count = 2; else count++; // **** update the max count (if needed) **** if (count > maxCount)
    				maxCount = count;
    		} 
    		
    		// **** reset the count ****
    		else {
    			count = 0;
    			fi 	  = i;
    		}
    		
//    		System.out.println("fi: " + fi + " i: " + i + " count: " + count + " maxCount: " + maxCount);
    	}
    		
    	// **** ****
    	return maxCount;
    }

My entire solution can be found in my GitHub repository. Please note that I made the necessary changes to the scaffolding code provided by HackerRank so I could run on Eclipse in my computer.

If you have comments / questions regarding this or any other post in this blog, please do not hesitate and leave me a note bellow. Notes are not made public unless I approve them. In addition, if you need some help with a software development project please let me know.

Keep on learning and developing great software.

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.