-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1502. Can Make Arithmetic Progression From Sequence.java
73 lines (53 loc) · 1.28 KB
/
1502. Can Make Arithmetic Progression From Sequence.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
//BRUTE FORCE SOLUTION - O(nlog n)
class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
Arrays.sort(arr);
int diff = arr[0]-arr[1];
for(int i=0;i<arr.length-1;i++)
{
if(arr[i]-arr[i+1]!=diff)
{
return false;
}
}
return true;
}
}
//Optimised - O(n)
class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++)
{
max = Math.max(max, arr[i]);
min = Math.min(min, arr[i]);
}
if((max-min)%(arr.length-1)!=0)
{
return false;
}
int d = (max - min) / (arr.length-1);
if(d==0)
{
return true;
}
HashSet<Integer> set = new HashSet<Integer>();
for(int i:arr)
{
set.add(i);
}
if(arr.length!=set.size())
{
return false;
}
for(int i=0;i<arr.length;i++)
{
if((arr[i]-min) % d != 0)
{
return false;
}
}
return true;
}
}