-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecondLargestinarray.cpp
60 lines (56 loc) · 1.09 KB
/
SecondLargestinarray.cpp
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
56
57
58
59
60
// You have been given a random integer array/list(ARR) of size N. You are required to find and return the second largest element present in the array/list.
// Sample Input 1:
// 5
// 4 3 10 9 2
// Sample Output 1:
// 9
// My Code:
int findSecondLargest(int arr[], int n)
{
//Write your code here
}
int findSecondLargest(int arr[], int n){
long a = 2147483648;
int count=0;int i=0,j=1;
for(j;j<n;j++){
if(arr[i] == arr[j]){
count++;
}
}
if((count)==n-1 || n <= 1)
return -a;
else{
int max = -9999999;
int j = 0;
for(int i = 0; i < n; i++){
if(arr[i] > max){
max = arr[i];
}
}
int temp = max;
max = -9999999;
for(int i = 0; i < n; i++){
if(arr[i] > max && arr[i] != temp){
max = arr[i];
}
}
return max;
}
}
// Main Code:
#include <iostream>
using namespace std;
#include "solution.h"
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int ans = findSecondLargest(arr, n);
cout<<ans;
return 0;
}