-2

We have to use an array as input and are supposed to output the second maximum element in it.

For instance if our input is a[]=10 20 30 40 50 60 70, the program should return 60. I've heard it's a very basic problem but I am new to java programming and can't figure it out.

Also, all elements are unique.

I've tried this so far and don't know how to proceed:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


     public static int SecondLargest(int[] arr) {
        int maxValue = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > maxValue) {
                maxValue = arr[i];
            }
        }
        return maxValue;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();

    }
}

1 Answers1

0
   int largest = null;
   int secondLargest = null;

   for(int i =0; i < array.length; i++)
   {
      if(largest = null)
      {
        largest = array[i];

      }
      else if(array[i] > largest)
     { 
         secondLargest = largest;
         largest = array[i];
      }
      else if(secondLargest == null || array[i] > secondLargest)
      {
        secondLargest = array[i];
      }
   } 
   return secondLargest

---Explanation We start out with both being null, We check in the loop if the largest is null then assign it to the first index; We check in the loop if the largest is null if not then if the largest is less than the currnt index if so we assign the second Largest equal to the largest then the largest equal to the current index. If the largest is greater than the current index and is not null we then check lastly if the second largest is less than the current index or null if so we assign it the value of the current index;

sdfbhg
  • 109
  • 5