I have an array which I would like to find the highest value for, but this value might be repeated.
For example, consider this array of integers:
{10, 2, 6, 25, 40, 58, 60, 60}.
//Here the value 60 is repeated
Here, I would like the output to show that there are two highest values in this array. Like in upper example it have to be show that 60 is highest value among all values in array and that value is 2 time available in array. And i do not want like to count how many numbers but like addition of that two highest numbers. I have search programs but i could not find any relevant solution for this.
class Cal
{
void CalculateThis()
{
int[] myArray = new int[] {20,10,5,40,20,41,41,2,6,7,3,4,5,6,23,34,7,8,9,2};
int max = Integer.MIN_VALUE;
int sum=0;
for(int i = 0; i < myArray.length; i++)
{
if(myArray[i] > max)
{
max = myArray[i]*3;
sum = sum + max;
}
}
System.out.println(sum);
}
}
class program1
{
public static void main(String args[])
{
Cal obj = new Cal();
obj.CalculateThis();
}
}
There are various approaches you could take here:
Arrays.sort
, then work from the end until you saw a different value... letting you work out the value and the count, which you could then multiply together. This is relatively inefficient, as you don't really need to sort.max
and the sum
at the same time, resetting both if you see a higher value. This will probably be the most efficient, but wouldn't be reusable for other requirements. (You could equivalently keep track of a count
as you went, and multiply the max
by count
at the end instead.)See more on this question at Stackoverflow