Finding the second highest number in array - java

I'm having difficulty to understand the logic behind the method to find the second highest number in array. The method used is to find the highest in the array but less than the previous highest (which has already been found). The thing that I still can't figure it out is why || highest_score == second_highest is necessary. For example I input three numbers: 98, 56, 3. Without it, both highest and second highest would be 98. Please explain.
int second highest = score[0];
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)
second_highest = score[i];

I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
This is O(N) in one pass. If you want to accept ties, then change to if (num >= high1), but as it is, it will return Integer.MIN_VALUE if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE if the array contains only the same number.

// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;
// Loop over the array
for (int i = 0; i < array.Length; i++) {
// If we've found a new highest number...
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (array[i] > secondHighest)
// Just replace the second highest
secondHighest = array[i];
}
}
// After exiting the loop, secondHighest now represents the second
// largest value in the array
Edit: Whoops. Thanks for pointing out my mistake, guys. Fixed now.

If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.
If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.

let array = [0,12,74,26,82,176,189,8,55,3,189];
let highest=0 ;
let secondHighest = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (highest > array[i] > secondHighest) {
// Just replace the second highest
secondHighest = array[i];
}
}
console.log(secondHighest);

The answers I saw wont work if there are two same largest numbers like the below example.
int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i: randomIntegers) {
set.add(i);
}
// Remove the maximum value; print the largest remaining item
set.remove(set.last());
System.out.println(set.last());
I have removed it from the Set not from the Array

My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.
public static int getMax22(int[] arr){
int max1 = arr[0];
int max2 = arr[1];
for (int i = 2; i < arr.length; i++){
if (arr[i] > max2)
{
max2 = arr[i];
}
if (max2 > max1)
{
int temp = max1;
max1 = max2;
max2 = temp;
}
}
return max2;
}

public static int secondLargest(int[] input) {
int largest,secondLargest;
if(input[0] > input[1]) {
largest = input[0];
secondLargest = input[1];
}
else {
largest = input[1];
secondLargest = input[0];
}
for(int i = 2; i < input.length; i++) {
if((input[i] <= largest) && input[i] > secondLargest) {
secondLargest = input[i];
}
if(input[i] > largest) {
secondLargest = largest;
largest = input[i];
}
}
return secondLargest;
}

import java.util.Scanner;
public class SecondHighestFromArrayTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of Array");
int size = scan.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
System.out.println("second highest element " + getSecondHighest(arr));
}
public static int getSecondHighest(int arr[]) {
int firstHighest = arr[0];
int secondHighest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = arr[i];
} else if (arr[i] > secondHighest) {
secondHighest = arr[i];
}
}
return secondHighest;
}
}

If time complexity is not an issue, then You can run bubble sort and within two iterations, you will get your second highest number because in the first iteration of the loop, the largest number will be moved to the last. In the second iteration, the second largest number will be moved next to last.

If you want to 2nd highest and highest number index in array then....
public class Scoller_student {
public static void main(String[] args) {
System.out.println("\t\t\tEnter No. of Student\n");
Scanner scan = new Scanner(System.in);
int student_no = scan.nextInt();
// Marks Array.........
int[] marks;
marks = new int[student_no];
// Student name array.....
String[] names;
names = new String[student_no];
int max = 0;
int sec = max;
for (int i = 0; i < student_no; i++) {
System.out.println("\t\t\tEnter Student Name of id = " + i + ".");
names[i] = scan.next();
System.out.println("\t\t\tEnter Student Score of id = " + i + ".\n");
marks[i] = scan.nextInt();
if (marks[max] < marks[i]) {
sec = max;
max = i;
} else if (marks[sec] < marks[i] && marks[max] != marks[i]) {
sec = i;
}
}
if (max == sec) {
sec = 1;
for (int i = 1; i < student_no; i++) {
if (marks[sec] < marks[i]) {
sec = i;
}
}
}
System.out.println("\t\t\tHigherst score id = \"" + max + "\" Name : \""
+ names[max] + "\" Max mark : \"" + marks[max] + "\".\n");
System.out.println("\t\t\tSecond Higherst score id = \"" + sec + "\" Name : \""
+ names[sec] + "\" Max mark : \"" + marks[sec] + "\".\n");
}
}

public class secondLargestElement
{
public static void main(String[] args)
{
int []a1={1,0};
secondHigh(a1);
}
public static void secondHigh(int[] arr)
{
try
{
int highest,sec_high;
highest=arr[0];
sec_high=arr[1];
for(int i=1;i<arr.length;i++)
{
if(arr[i]>highest)
{
sec_high=highest;
highest=arr[i];
}
else
// The first condition before the || is to make sure that second highest is not actually same as the highest , think
// about {5,4,5}, you don't want the last 5 to be reported as the sec_high
// The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
// Think about {5,5,4}
if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
sec_high=arr[i];
}
//System.out.println("high="+highest +"sec"+sec_high);
if(highest==sec_high)
System.out.println("All the elements in the input array are same");
else
System.out.println("The second highest element in the array is:"+ sec_high);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Not enough elements in the array");
//e.printStackTrace();
}
}
}

You can find Largest and Third largest number of unsorted array as well.
public class ThirdLargestNumber {
public static void main(String[] args) {
int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
for (int i = 0; i <= 9 /*
* Length of array-1. You can use here length
* property of java array instead of hard coded
* value
*/; i++) {
if (arr[i] == first) {
continue;
}
if (arr[i] > first) {
firstTemp = first;
secondTemp = second;
first = arr[i];
second = firstTemp;
if (secondTemp > third) {
third = secondTemp;
}
} else {
if ((arr[i] == second) || (arr[i]) == first) {
continue;
}
if ((arr[i] > second) && (arr[i]) < first) {
secondTemp = second;
second = arr[i];
if (secondTemp > third) {
third = secondTemp;
}
} else {
if (arr[i] > third) {
third = arr[i];
}
}
}
}
// System.out.println("Third largest number: " + third);
System.out.println("Second largest number: " + second);
// System.out.println("Largest number: " + first);
}
}

I think for finding the second Highest no we require these lines,if we can use inbuilt function
int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
Arrays.sort(randomIntegers);
System.out.println(randomIntegers[randomIntegers.length-2]);

I am giving solution that's not in JAVA program (written in JavaScript), but it takes o(n/2) iteration to find the highest and second highest number.
Working fiddler link Fiddler link
var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1], seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
if(num[i] < num[j] )
{
if(firstHighest < num[j]){
seoncdHighest=firstHighest;
firstHighest= num[j];
}
else if(seoncdHighest < num[j] ) {
seoncdHighest= num[j];
}
}
else {
if(firstHighest < num[i])
{
seoncdHighest=firstHighest;
firstHighest= num[i];
}
else if(seoncdHighest < num[i] ) {
seoncdHighest= num[i];
}
}
}

public class SecondandThirdHighestElement {
public static void main(String[] args) {
int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
// create three temp variable and store arr of first element in that temp variable so that it will compare with other element
int firsttemp = arr[0];
int secondtemp = arr[0];
int thirdtemp = arr[0];
//check and find first highest value from array by comparing with other elements if found than save in the first temp variable
for (int i = 0; i < arr.length; i++) {
if(firsttemp <arr[i]){
firsttemp = arr[i];
}//if
}//for
//check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
for (int i = 0; i < arr.length; i++) {
if(secondtemp < arr[i] && firsttemp>arr[i]){
secondtemp = arr[i];
}//if
}//for
//check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array
for (int i = 0; i < arr.length; i++) {
if(thirdtemp < arr[i] && secondtemp>arr[i]){
thirdtemp = arr[i];
}//if
}//for
System.out.println("First Highest Value:"+firsttemp);
System.out.println("Second Highest Value:"+secondtemp);
System.out.println("Third Highest Value:"+thirdtemp);
}//main
}//class

If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.
public void printLargest(){
int num[] ={ 900,90,6,7,5000,4,60000,20,3};
int largest = num[0];
int secondLargest = num[1];
for (int i=1; i<num.length; i++)
{
if(largest < num[i])
{
secondLargest = largest;
largest = num[i];
}
else if(secondLargest < num[i]){
secondLargest = num[i];
}
}
System.out.println("Largest : " +largest);
System.out.println("Second Largest : "+secondLargest);
}

Problem:
The problem is to get the second largest array element.
Observation:
Second largest number is defined as the number that has the minimum difference when subtracted from the maximum element in the array.
Solution:
This is a two pass solution. First pass is to find the maximum number. Second pass is to find the element that has minimum difference with the maximum element as compared to other array elements. Example: In the array [2, 3, 6, 6, 5] maximum = 6 and second maximum = 5 , since it has the minimum difference to the maximum element 6 - 5 = 1 the solution for second largest = 5
function printSecondMax(myArray) {
var x, max = myArray[0];
// Find maximum element
for(x in myArray){
if(max < myArray[x]){
max = myArray[x];
}
}
var secondMax = myArray[0], diff = max - secondMax;
// Find second max, an element that has min diff with the max
for(x in myArray){
if(diff != 0 && (max - myArray[x]) != 0 && diff > (max - myArray[x])){
secondMax = myArray[x];
diff = max - secondMax;
}
}
console.log(secondMax);
}
Complexity : O(n), This is the simplest way to do this.
For finding maximum element even more efficiently one can look into max heap, a call to max-heapify will take O(log n) time to find the max and then pop-ing the top element gives maximum. To get the second maximum, max-heapify after pop-ing the top and keep pop-ing till you get a number that is less than maximum. That will be the second maximum. This solution has O(n log n) complexity.

private static int SecondBiggest(int[] vector)
{
if (vector == null)
{
throw new ArgumentNullException("vector");
}
if (vector.Length < 2)
{
return int.MinValue;
}
int max1 = vector[0];
int max2 = vector[1];
for (int i = 2; i < vector.Length; ++i)
{
if (max1 > max2 && max1 != vector[i])
{
max2 = Math.Max(max2, vector[i]);
}
else if (max2 != vector[i])
{
max1 = Math.Max(max1, vector[i]);
}
}
return Math.Min(max1, max2);
}
This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.

Please try this one: Using this method, You can fined second largest number in array even array contain random number. The first loop is used to solve the problem if largest number come first index of array.
public class secondLargestnum {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = new int[6];
array[0] = 10;
array[1] = 80;
array[2] = 5;
array[3] = 6;
array[4] = 50;
array[5] = 60;
int tem = 0;
for (int i = 0; i < array.length; i++) {
if (array[0]>array[i]) {
tem = array[0];
array[0] = array[array.length-1];
array[array.length-1] = tem;
}
}
Integer largest = array[0];
Integer second_largest = array[0];
for (int i = 0; i < array.length; i++) {
if (largest<array[i]) {
second_large = largest;
largest = array[i];
}
else if (second_large<array[i]) {
second_large = array[i];
}
}
System.out.println("largest number "+largest+" and second largest number "+second_largest);
}
}

public class SecondHighInIntArray {
public static void main(String[] args) {
int[] intArray=new int[]{2,2,1};
//{2,2,1,12,3,7,9,-1,-5,7};
int secHigh=findSecHigh(intArray);
System.out.println(secHigh);
}
private static int findSecHigh(int[] intArray) {
int highest=Integer.MIN_VALUE;
int sechighest=Integer.MIN_VALUE;
int len=intArray.length;
for(int i=0;i<len;i++)
{
if(intArray[i]>highest)
{
sechighest=highest;
highest=intArray[i];
continue;
}
if(intArray[i]<highest && intArray[i]>sechighest)
{
sechighest=intArray[i];
continue;
}
}
return sechighest;
}
}

Second Largest in O(n/2)
public class SecMaxNum {
// second Largest number with O(n/2)
/**
* #author Rohan Kamat
* #Date Feb 04, 2016
*/
public static void main(String[] args) {
int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
int large = 0, second = 0;
for (int i = 0; i < input.length - 1; i = i + 2) {
// System.out.println(i);
int fist = input[i];
int sec = input[i + 1];
if (sec >= fist) {
int temp = fist;
fist = sec;
sec = temp;
}
if (fist >= second) {
if (fist >= large) {
large = fist;
} else {
second = fist;
}
}
if (sec >= second) {
if (sec >= large) {
large = sec;
} else {
second = sec;
}
}
}
}
}

public class SecondHighest {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* Find the second largest int item in an unsorted array.
* This solution assumes we have atleast two elements in the array
* SOLVED! - Order N.
* Other possible solution is to solve with Array.sort and get n-2 element.
* However, Big(O) time NlgN
*/
int[] nums = new int[]{1,2,4,3,5,8,55,76,90,34,91};
int highest,cur, secondHighest = -1;
int arrayLength = nums.length;
highest = nums[1] > nums[0] ? nums[1] : nums[0];
secondHighest = nums[1] < nums[0] ? nums[1] : nums[0];
if (arrayLength == 2) {
System.out.println(secondHighest);
} else {
for (int x = 0; x < nums.length; x++) {
cur = nums[x];
int tmp;
if (cur < highest && cur > secondHighest)
secondHighest = cur;
else if (cur > secondHighest && cur > highest) {
tmp = highest;
highest = cur;
secondHighest = tmp;
}
}
System.out.println(secondHighest);
}
}
}

Use following function
`
public static int secHigh(int arr[]){
int firstHigh = 0,secHigh = 0;
for(int x: arr){
if(x > firstHigh){
secHigh = firstHigh;
firstHigh = x;
}else if(x > secHigh){
secHigh = x;
}
}
return secHigh;
}
Function Call
int secondHigh = secHigh(arr);

import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array : ");
int n = sc.nextInt();
int ar[] = new int[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter value for array : ");
ar[i] = sc.nextInt();
}
int m=ar[0],m2=ar[0];
for(int i=0;i<n;i++)
{
if(ar[i]>m)
m=ar[i];
}
for(int i=0;i<n;i++)
{
if(ar[i]>m2 && ar[i]<m)
m2=ar[i];
}
System.out.println("Second largest : "+m2);
sc.close();
}
}

public void findMax(int a[]) {
int large = Integer.MIN_VALUE;
int secondLarge = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (large < a[i]) {
secondLarge = large;
large = a[i];
} else if (a[i] > secondLarge) {
if (a[i] != large) {
secondLarge = a[i];
}
}
}
System.out.println("Large number " + large + " Second Large number " + secondLarge);
}
The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrived in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.

public class SecondLargestNumber
{
public static void main(String[] args)
{
int[] var={-11,-11,-11,-11,115,-11,-9};
int largest = 0;
int secLargest = 0;
if(var.length == 1)
{
largest = var[0];
secLargest = var[0];
}
else if(var.length > 1)
{
largest= var[0];
secLargest = var[1];
for(int i=1;i<var.length;i++)
{
if(secLargest!=largest)
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else if(var[i]>secLargest && var[i] != largest)
{
secLargest= var[i];
}
}
else
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else
{
secLargest = var[i];
}
}
}
}
System.out.println("Largest: "+largest+" Second Largest: "+secLargest);
}
}

/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
int i, first, second;
/* There should be atleast two elements */
if (arr_size < 2)
{
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN)
printf("There is no second largest elementn");
else
printf("The second largest element is %dn", second);
}

I have got the simplest logic to find the second largest number may be, it's not.
The logic find sum of two number in the array which has the highest value and then check which is greater among two simple............
int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
for(int j=i;j<ar.length;j++){
if(i!=j){
temp=ar[i]+ar[j];
if(temp>sum){
sum=temp;
m=ar[i];
n=ar[j];
}
temp=0;
}
}
}
if(m>n){
System.out.println(n);
}
else{
System.out.println(m);
}

The simplest way is -
public class SecondLargest {
public static void main(String[] args) {
int[] arr = { 1, 2, 5, 6, 3 };
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
// If current element is smaller than first then update both first
// and second
if (arr[i] > first) {
second = first;
first = arr[i];
}
// If arr[i] is in between first and second then update second
else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
}
}

The second largest element in the array :
IN Java:
class test2{
public static void main(String[] args) {
int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
int aa = a[a.length -2 ];
System.out.println(aa);
}//main
}//end
In Python :
a = [1, 2, 3, 9, 5, 7, 6, 4, 8]
aa = sorted(list(a))
print(aa)
aaa = aa[-2]
print(aaa)

Related

Finding largest gap between consecutive numbers in array Java

I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15

Find the max value of the same length nails after hammered

I'm trying to solve this problem:
Given an array of positive integers, and an integer Y, you are allowed to replace at most Y array-elements with lesser values. Your goal is for the array to end up with as large a subset of identical values as possible. Return the size of this largest subset.
The array is originally sorted in increasing order, but you do not need to preserve that property.
So, for example, if the array is [10,20,20,30,30,30,40,40,40] and Y = 3, the result should be 6, because you can get six 30s by replacing the three 40s with 30s. If the array is [20,20,20,40,50,50,50,50] and Y = 2, the result should be 5, because you can get five 20s by replacing two of the 50s with 20s.
Below is my solution with O(nlogn) time complexity. (is that right?) I wonder if I can further optimize this solution?
Thanks in advance.
public class Nails {
public static int Solutions(int[] A, int Y) {
int N = A.length;
TreeMap < Integer, Integer > nailMap = new TreeMap < Integer, Integer > (Collections.reverseOrder());
for (int i = 0; i < N; i++) {
if (!nailMap.containsKey(A[i])) {
nailMap.put(A[i], 1);
} else {
nailMap.put(A[i], nailMap.get(A[i]) + 1);
}
}
List < Integer > nums = nailMap.values().stream().collect(Collectors.toList());
if (nums.size() == 1) {
return nums.get(0);
}
//else
int max = nums.get(0);
int longer = 0;
for (int j = 0; j < nums.size(); j++) {
int count = 0;
if (Y < longer) {
count = Y + nums.get(j);
} else {
count = longer + nums.get(j);
}
if (max < count) {
max = count;
}
longer += nums.get(j);
}
return max;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String[] input = scanner.nextLine().replaceAll("\\[|\\]", "").split(",");
System.out.println(Arrays.toString(input));
int[] A = new int[input.length - 1];
int Y = Integer.parseInt(input[input.length - 1]);
for (int i = 0; i < input.length; i++) {
if (i < input.length - 1) {
A[i] = Integer.parseInt(input[i]);
} else {
break;
}
}
int result = Solutions(A, Y);
System.out.println(result);
}
}
}
A C++ implementation would like the following where A is the sorted pin size array and K is the number of times the pins can be hammered.
{1,1,3,3,4,4,4,5,5}, K=2 should give 5 as the answer
{1,1,3,3,4,4,4,5,5,6,6,6,6,6,6}, K=2 should give 6 as the answer
int maxCount(vector<int>& A, int K) {
int n = A.size();
int best = 0;
int count = 1;
for (int i = 0; i < n-K-1; i++) {
if (A[i] == A[i + 1])
count = count + 1;
else
count = 1;
if (count > best)
best = count;
}
int result = max(best+K, min(K+1, n));
return result;
}
Since the array is sorted to begin with, a reasonably straightforward O(n) solution is, for each distinct value, to count how many elements have that value (by iteration) and how many elements have a greater value (by subtraction).
public static int doIt(final int[] array, final int y) {
int best = 0;
int start = 0;
while (start < array.length) {
int end = start;
while (end < array.length && array[end] == array[start]) {
++end;
}
// array[start .. (end-1)] is now the subarray consisting of a
// single value repeated (end-start) times.
best = Math.max(best, end - start + Math.min(y, array.length - end));
start = end; // skip to the next distinct value
}
assert best >= Math.min(y + 1, array.length); // sanity-check
return best;
}
First, iterate through all the nails and create a hash H that stores the number of nails for each size. For [1,2,2,3,3,3,4,4,4], H should be:
size count
1 : 1
2 : 2
3 : 3
4 : 3
Now create an little algorithm to evaluate the maximum sum for each size S, given Y:
BestForSize(S, Y){
total = H[S]
while(Y > 0){
S++
if(Y >= H[S] and S < biggestNailSize){
total += H[S]
Y -= H[S]
}
else{
total += Y
Y = 0
}
}
return total;
}
Your answer should be max(BestForSize(0, Y), BestForSize(1, Y), ..., BestForSize(maxSizeOfNail, Y)).
The complexity is O(n²). A tip to optimize is to start from the end. For example, after you have the maximum value of nails in the size 4, how can you use your answer to find the maximum number of size 3?
Here is my java implementation: First I build a reversed map of each integer and its occurence for example {1,1,1,1,3,3,4,4,5,5} would give {5=2, 4=2, 3=2, 1=4}, then for each integer I calculate the max occurence that we can get of it regarding the K and the occurences of the highest integers in the array.
public static int ourFunction(final int[] A, final int K) {
int length = A.length;
int a = 0;
int result = 0;
int b = 0;
int previousValue = 0;
TreeMap < Integer, Integer > ourMap = new TreeMap < Integer, Integer > (Collections.reverseOrder());
for (int i = 0; i < length; i++) {
if (!ourMap.containsKey(A[i])) {
ourMap.put(A[i], 1);
} else {
ourMap.put(A[i], ourMap.get(A[i]) + 1);
}
}
for (Map.Entry<Integer, Integer> entry : ourMap.entrySet()) {
if( a == 0) {
a++;
result = entry.getValue();
previousValue = entry.getValue();
} else {
if( K < previousValue)
b = K;
else
b = previousValue;
if ( b + entry.getValue() > result )
result = b + entry.getValue();
previousValue += entry.getValue();
}
}
return result;
}
Since the array is sorted, we can have an O(n) solution by iterating and checking if current element is equals to previous element and keeping track of the max length.
static int findMax(int []a,int y) {
int n = a.length,current = 1,max = 0,diff = 0;
for(int i = 1; i< n; i++) {
if(a[i] == a[i-1]) {
current++;
diff = Math.min(y, n-i-1);
max = Math.max(max, current+diff);
}else {
current = 1;
}
}
return max;
}
given int array is not sorted than you should sort
public static int findMax(int []A,int K) {
int current = 1,max = 0,diff = 0;
List<Integer> sorted=Arrays.stream(A).sorted().boxed().collect(Collectors.toList());
for(int i = 1; i< sorted.size(); i++) {
if(sorted.get(i).equals(sorted.get(i-1))) {
current++;
diff = Math.min(K, sorted.size()-i-1);
max = Math.max(max, current+diff);
}else {
current = 1;
}
}
return max;
}
public static void main(String args[]) {
List<Integer> A = Arrays.asList(3,1,5,3,4,4,3,3,5,5,5,1);
int[] Al = A.stream().mapToInt(Integer::intValue).toArray();
int result=findMax(Al, 5);
System.out.println(result);
}

Returning the index of the n-th highest value of an unsorted list

I have written the following code and am now trying to figure out the best way to achieve what is explained in the four comments:
Integer[] expectedValues = new Integer[4];
for (int i = 0; i <= 3; i++) {
expectedValues[i] = getExpectedValue(i);
}
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
// return index of highest value in expectedValues
} else if (choice <= intelligence * 2) {
// return index of 2nd highest value in expectedValues
} else if (choice <= intelligence * 3) {
// return index of 3rd highest value in expectedValues
} else {
// return index of lowest value in expectedValues
}
What would be an elegant way o doing so? I do not need to keep expected values as an array - I am happy to use any data structure.
You could create a new array containing the indices and sort on the values - in semi-pseudo code it could look like this (to be adapted):
int[][] valueAndIndex = new int[n][2];
//fill array:
valueAndIndex[i][0] = i;
valueAndIndex[i][1] = expectedValues[i];
//sort on values in descending order
Arrays.sort(valueAndIndex, (a, b) -> Integer.compare(b[1], a[1]));
//find n-th index
int n = 3; //3rd largest number
int index = valueAndIndex[n - 1][0];
If you want to work with simple arrays, maybe this might be a solution:
public static void main(String[] args) {
int[] arr = new int[] { 1, 4, 2, 3 };
int[] sorted = sortedCopy(arr);
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
System.out.println(findIndex(arr, sorted[3])); // 1
} else if (choice <= intelligence * 2) {
System.out.println(findIndex(arr, sorted[2])); // 3
} else if (choice <= intelligence * 3) {
System.out.println(findIndex(arr, sorted[1])); // 2
} else {
System.out.println(findIndex(arr, sorted[0])); // 0
}
}
static int[] sortedCopy(int[] arr) {
int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);
Arrays.sort(copy);
return copy;
}
static int findIndex(int[] arr, int val) {
int index = -1;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == val) {
index = i;
break;
}
}
return index;
}
You can "wipe out" the highest value n-1 times. After this the highest value is the n-th highest value of the original array:
public static void main(String[] args) {
int[] numbers = new int[]{5, 9, 1, 4};
int n = 2; // n-th index
for (int i = 0; i < n - 1; ++i) {
int maxIndex = findMaxIndex(numbers);
numbers[maxIndex] = Integer.MIN_VALUE;
}
int maxIndex = findMaxIndex(numbers);
System.out.println(maxIndex + " -> " + numbers[maxIndex]);
}
public static int findMaxIndex(int[] numbers) {
int maxIndex = 0;
for (int j = 1; j < numbers.length; ++j) {
if (numbers[j] > numbers[maxIndex]) {
maxIndex = j;
}
}
return maxIndex;
}
The complexity is O(n * numbers.length).

How to swap the position of the numbers

I'm new to Java programming and I want to know how to swap the position of the highest number and the lowest number.
import java.util.*;
public class HighestandLowestNum
{
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num [] = new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i < num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.println("The highest number is: " + Highest(num));
System.out.println("The lowest number is: " + Lowest(num));
}
public static int Highest(int[] num)
{
int highest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] > highest)
{
highest = num[i];
}
}
return highest;
}
public static int Lowest(int[] num)
{
int lowest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] < lowest)
{
lowest = num[i];
}
}
return lowest;
}
}
This is my program. Please help me to fix my problem.
Your two functions Highest and Lowest return the value of the highest and lowest numbers. In order to swap them, you need to know the positions those values have within the array.
If you alter those functions or create new ones to return the index of the highest and lowest values, then you can swap them with what you've probably already seen before:
pseudocode:
temp = first
first = last
last = temp
To Swap the two numbers in the array, you need to know the numbers and their position as mentioned in the earlier answers. You can modify the two functions in such a way that they provide Numbers as well as their Position. One way to do this is to return an array instead of integer from the function. And in that array, information about the number and its position can be encapsulated. Ill show you what I mean in the code I am providing:
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num []= new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i <num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.print("The original array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
System.out.println("");
int highest = Highest(num)[0];
int lowest = Lowest(num)[0];
int highestPosition = Highest(num)[1];
int lowestPosition = Lowest(num)[1];
System.out.println("The highest number is: " +highest+" at position "+highestPosition);
System.out.println("The lowest number is: " +lowest+" at position "+lowestPosition);
//Swap//
num[highestPosition] = lowest;
num[lowestPosition] = highest;
System.out.print("The new array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
}
public static int[] Highest(int[] num)
{
int highest = num[0];
int i;
int index = 0;
int[] result = {highest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] > highest)
{
highest = num[i];
index = i;
result[0] = highest;
result[1] = index;
}
}
return result;
}
public static int[] Lowest(int[] num)
{
int lowest = num[0];
int i;
int index = 0;
int[] result = {lowest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] < lowest)
{
lowest = num[i];
index = i;
result[0] = lowest;
result[1] = index;
}
}
return result;
}
Try reading the modification in the Highest and Lowest functions and than go through the main code. Hope this helps.

Getting the largest element in an array using recursion

I have an assignment to use recursion to obtain the largest element in any given array. I have the following code which will work unless the largest element is the last in the array.
Not sure how to correct this?
import java.util.Scanner;
public class RecursionLargestInArray
{
public static void main (String[] args)
{
int max = -999;
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < myArray.length; i++)
myArray[i] = scan.nextInt();
for (int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
System.out.println("In the array entered, the larget value is "
+ getLargest(myArray, max) + ".");
}
public static int getLargest(int[] myArray, int max)
{
int i = 0, j = 0, tempmax = 0;
if (myArray.length == 1)
{
return max;
}
else if (max < myArray[i])
{
max = myArray[i];
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
else if
{
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
}
}
Your first condition is the problem:
if (myArray.length == 1)
{
return max;
}
replace it with:
if (myArray.length == 1)
{
return myArray[0] > max ? myArray[0] : max;
}
In case of an array with only one element, you return the previous maximum. If the max is that last element, it will be skipped.
you never evaluate the final element - you simply return max when the size of the array is 1, so you never actually check the final element in the array.
also, a comment - rather than creating copies of the array each time, why don't you simply pass the current index into your function every time you recurse?
When the array length is 1, getLargest isn't testing the (single) array element against max; it's just returning max. That's why it's always skipping the last element.
As an aside, it would be better to initialize max to Integer.MIN_VALUE instead of to an arbitrary value of -999.
As a further aside, once you get your code working, it will still be terribly inefficient. You might consider posting it to codereview.stackexchange.com to get feedback.
how about divide and conquer?
private static int findLargest(int lowerLimit, int upperLimit) {
if (lowerLimit == upperLimit) {
return temp[lowerLimit];
} else if (upperLimit - lowerLimit == 1){
return Math.max(temp[upperLimit], temp[lowerLimit]);
} else {
int pivot = (upperLimit - lowerLimit + 1)/2;
int firstHalf = findLargest(lowerLimit, lowerLimit + pivot);
int secondHalf = findLargest(upperLimit - pivot , upperLimit);
return Math.max(firstHalf, secondHalf);
}
}
of course temp is the global array.. and to start the recursion you call it with findLargest(0,temp.length)

Categories

Resources