class Solution:
def canMakeArithmeticProgression(self, arr):
arr.sort()
diff = arr[1] - arr[0]
for i in range(2, len(arr)):
if arr[i] - arr[i-1] != diff:
return False
return True
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
sort(arr.begin(), arr.end());
int diff = arr[1] - arr[0];
for (int i = 2; i < arr.size(); ++i) {
if (arr[i] - arr[i-1] != diff) return false;
}
return true;
}
};
import java.util.*;
class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
Arrays.sort(arr);
int diff = arr[1] - arr[0];
for (int i = 2; i < arr.length; i++) {
if (arr[i] - arr[i-1] != diff) return false;
}
return true;
}
}
/**
* @param {number[]} arr
* @return {boolean}
*/
var canMakeArithmeticProgression = function(arr) {
arr.sort((a, b) => a - b);
let diff = arr[1] - arr[0];
for (let i = 2; i < arr.length; i++) {
if (arr[i] - arr[i-1] !== diff) return false;
}
return true;
};
You are given an array of numbers, named arr
. Your task is to determine if you can reorder the elements of arr
(i.e., arrange them in any order) so that the resulting sequence forms an arithmetic progression.
An arithmetic progression is a sequence where the difference between any two consecutive elements is always the same. For example, [3, 5, 7, 9] is an arithmetic progression with a common difference of 2.
The first thought might be to try all possible permutations of the array and check if any of them form an arithmetic progression. However, this brute-force approach is inefficient, especially for larger arrays, since the number of permutations grows factorially with the array size.
Instead, let's consider the properties of an arithmetic progression. If we sort the array, then for it to be an arithmetic progression, the difference between each consecutive pair must be the same. This insight allows us to reduce the problem to a simple check after sorting.
By focusing on the sorted version, we avoid the need to try every permutation, and we can check the condition in a single pass.
To solve this problem efficiently, follow these steps:
This approach is efficient because:
Let's consider the input arr = [3, 5, 1]
:
If we try an array like arr = [1, 2, 4]
:
Since not all differences are equal, return false.
Brute-force approach:
The optimized approach is much faster and more practical for larger arrays.
To determine if an array can form an arithmetic progression, we can sort the array and check if all consecutive differences are the same. This insight allows us to move from a brute-force, inefficient solution to a simple and elegant one that is efficient and easy to implement. The key is recognizing that sorting reveals the only possible order for an arithmetic progression and that the condition can be checked in a single scan.