-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxSecondMaxinArray.java
More file actions
55 lines (48 loc) · 1.4 KB
/
maxSecondMaxinArray.java
File metadata and controls
55 lines (48 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package dsa;
import java.util.ArrayList;
/**
*
* @author Admin
*/
public class maxSecondMaxinArray
{
//should return maximum and second maximum element from the array
public static ArrayList<Integer> largestAndSecondLargest(int sizeOfArray, int arr[])
{
int max=Integer.MIN_VALUE;
int sMax=Integer.MIN_VALUE;
ArrayList<Integer> ans=new ArrayList<Integer>();
for(int i=0;i<sizeOfArray;i++)
{
if(arr[i]>max)
{
sMax=max;
max=arr[i];
}
else if((arr[i]>sMax) && (arr[i]<max))
{
sMax=arr[i];
}
}
if(sMax==Integer.MIN_VALUE)
{
sMax=-1; //If no second max exists, then the second max will be -1
}
ans.add(max);
ans.add(sMax);
return ans;
}
public static void main(String[] args)
{
int[] a={10,10,10,10,10};
int n=a.length;
ArrayList<Integer> ans=new ArrayList<Integer>();
ans=largestAndSecondLargest(n,a);
//TC:O(N)
System.out.println(ans);
}
}