forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcan-make-arithmetic-progression-from-sequence.java
More file actions
50 lines (38 loc) · 1.14 KB
/
can-make-arithmetic-progression-from-sequence.java
File metadata and controls
50 lines (38 loc) · 1.14 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
/**
Approach is to use AP formula
Sum = n/2(a+l)
where sum will be sum of all elements
n will be number of elements
a will be minimum element
l will be maximum element
if both LHS & RHS values are equal then return true, else false.
*/
class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
int n = arr.length;
double sumOfMaxAndMin = 0;
int sum = arr[0];
int max = arr[0];
int min = arr[0];
// Traverse the array and find out sum, max & min
for (int i=1; i<n; i++){
sum += arr[i];
if (max < arr[i]){
max = arr[i];
}
if (arr[i] < min){
min = arr[i];
}
}
// add max & min -> also they are first & last element
sumOfMaxAndMin = max + min;
// multiply above value with n
sumOfMaxAndMin *= n;
// divide above value with 2
sumOfMaxAndMin /= 2;
if (sum == sumOfMaxAndMin){
return true;
}
return false;
}
}