File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments