SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Implementing A Collection Class
Exercise:
Exercises
Question:7 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to the ArrayIntList class from this chapter.

Write a method called maxCount that returns the number of occurrences of the most frequently occurring value in a sorted list of integers. Because the list will be sorted, all duplicates will be grouped together, which will make it easier to count duplicates. For example, if a variable called list stores [1, 3, 4, 7, 7, 7, 7, 9, 9, 11, 13, 14, 14, 14, 16, 16, 18, 19, 19, 19] , the call of list.maxCount() should return 4 because the most frequently occurring value ( 7 ) occurs four times. It is possible that there will be a tie for the most frequently occurring value, but that doesn’t affect the outcome because you are just returning the count, not the value. If there are no duplicates in the list, then every value will occur exactly once and the max count is 1 . If the list is empty, the method should return 0 .

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of maxCount method:

	public int maxCount()
	{
		if(size == 0)
			return 0;

		int longest = 1;
		int count = 1;

		for(int i = 1; i < size; i++)
		{
			if(elementData[i] == elementData[i - 1])
				count++;
			else
				count = 1;

			if(count > longest)
				longest = count;
		}

		return longest;
	}
0 0

Discussions

Post the discussion to improve the above solution.