Skip to content

Commit 548f7d3

Browse files
new file added
1 parent 39607ad commit 548f7d3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
Approach is to use AP formula
3+
Sum = n/2(a+l)
4+
5+
where sum will be sum of all elements
6+
n will be number of elements
7+
a will be minimum element
8+
l will be maximum element
9+
10+
if both LHS & RHS values are equal then true else false.
11+
*/
12+
class Solution {
13+
public boolean canMakeArithmeticProgression(int[] arr) {
14+
int n = arr.length;
15+
16+
double sumOfMaxAndMin = 0;
17+
18+
int sum = arr[0];
19+
int max = arr[0];
20+
int min = arr[0];
21+
22+
// Traverse the array and find out sum, max & min
23+
for (int i=1; i<n; i++){
24+
sum += arr[i];
25+
26+
if (max < arr[i]){
27+
max = arr[i];
28+
}
29+
30+
if (arr[i] < min){
31+
min = arr[i];
32+
}
33+
}
34+
35+
// add max & min -> also they are first & last element
36+
sumOfMaxAndMin = max + min;
37+
38+
// multiply above value with n
39+
sumOfMaxAndMin *= n;
40+
41+
// divide above value with 2
42+
sumOfMaxAndMin /= 2;
43+
44+
if (sum == sumOfMaxAndMin){
45+
return true;
46+
}
47+
48+
return false;
49+
}
50+
}

0 commit comments

Comments
 (0)