-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProblem-2.java
136 lines (88 loc) · 2.54 KB
/
Problem-2.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* @author AkashGoyal
* @date 24/05/2021
*/
/**
--------------------- Problem----------->> Find minimum and maximum element in an array
Problem Link :- https://practice.geeksforgeeks.org/problems/find-minimum-and-maximum-element-in-an-array4428/1#
*/
//Method-1
class Compute
{
static pair getMinMax(long a[], long n)
{
long max=0;
long min=Integer.MAX_VALUE;
for(int i=0;i<a.length;i++)
{
if(a[i]<min)
{
min=a[i];
}
if(a[i]>max)
{
max=a[i];
}
}
return new pair(min,max);
}
}
//-----------------------------------------------------------------------------------------------------------
//Method-2 O(n)--> Minimum Swap
class Compute
{
static pair getMinMax(long a[], long n)
{
/*
// Solution with Minimum comparisions
1 2 3 4 = 8
1 2 => 1
3 4 => 1
1 2 3 4 => 2
total = 4
(3*n)/2-2
if n is power of 2;
otherwise
>(3*n)/2-2*/
return MinMax(a, 0, (int)(n-1));
}
static pair MinMax(long a[],int low, int high)
{
pair minmaxleft=new pair(0,0);
pair minmaxright=new pair(0,0);
//only one element
if(low==high)
{
minmaxleft.first=a[low];
minmaxright.second=a[high];
return new pair(minmaxleft.first,minmaxright.second);
}
//two element
if(low==high-1)
{
if(a[low]<a[high])
{
minmaxleft.first=a[low];
minmaxright.second=a[high];
}
else
{
minmaxleft.first=a[high];
minmaxright.second=a[low];
}
return new pair(minmaxleft.first,minmaxright.second);
}
//More then two elements
int mid=low+(high-low)/2;
minmaxleft=MinMax(a,low,mid);
minmaxright=MinMax(a,mid+1,high);
if(minmaxleft.first<minmaxright.first)
{
minmaxright.first=minmaxleft.first;
}
if(minmaxleft.second>minmaxright.second){
minmaxright.second=minmaxleft.second;
}
return new pair(minmaxright.first,minmaxright.second);
}
}