Max and Second Max

PHOTO EMBED

Tue Feb 08 2022 06:26:48 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #arrays #practice #max #secondmax

class Solution{
    
    // Function to find largest and second largest element in the array
    public static ArrayList<Integer> largestAndSecondLargest(int sizeOfArray, int arr[])
       {
           //code here.
           int largest=-1;
           int sec_largest=-1;
           for(int i=0;i<sizeOfArray;i++)
           {
               largest = Math.max(largest,arr[i]);
           }
           for(int i=0;i<sizeOfArray;i++)
           {
               if(arr[i]<largest)
               {
                   sec_largest= Math.max(sec_largest,arr[i]);
               }
           }
           ArrayList<Integer> al = new ArrayList<Integer>(2);
           al.add(largest);
           al.add(sec_largest);
           return al;
       }
    }
}
content_copyCOPY

Max and Second Max Given an array arr[] of size N of positive integers which may have duplicates. The task is to find the maximum and second maximum from the array, and both of them should be distinct, so If no second max exists, then the second max will be -1. Example 1: Input: N = 3 arr[] = {2,1,2} Output: 2 1 Explanation: From the given array elements, 2 is the largest and 1 is the second largest. Example 2: Input: N = 5 arr[] = {1,2,3,4,5} Output: 5 4 Explanation: From the given array elements, 5 is the largest and 4 is the second largest. Your Task: The task is to complete the function largestAndSecondLargest(), which should return maximum and second maximum element from the array with first element as maximum element and second element as second maximum(if there is no second maximum the second element should be -1) Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 <= N <= 10^6 1 <= arr[i] <= 10^6

https://practice.geeksforgeeks.org/problems/max-and-second-max/1/?track=DSASP-Arrays&batchId=190