A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers arr
, return true
if the array can be rearranged to form an arithmetic progression. Otherwise, return false
.
class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int a : arr) {
arrayList.add(a);
}
Collections.sort(arrayList);
int subtracted = arrayList.get(1) - arrayList.get(0);
if (arrayList.size() == 2) {
return true;
}
for (int i = 1; i < arrayList.size() - 1; i++) {
if (subtracted != arrayList.get(i + 1) - arrayList.get(i)) {
return false;
}
}
return true;
}
}