Leetcode 1502. Can Make Arithmetic Progression From Sequence
Given an array of numbers arr (of length at least 2), determine whether it is possible to reorder the elements of arr to form an arithmetic progression. An arithmetic progression is a sequence of numbers such that the difference between consecutive terms is constant.
Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1], both form a valid arithmetic progression.
arr can be rearranged.true or false).O(n log n).O(n).O(n log n).#include <vector>
#include <algorithm>
using namespace std;
bool canMakeArithmeticProgression(vector<int>& arr) {
// Sort the array
sort(arr.begin(), arr.end());
// Calculate the common difference
int commonDiff = arr[1] - arr[0];
// Check the difference between each consecutive elements
for (int i = 2; i < arr.size(); i++) {
if (arr[i] - arr[i - 1] != commonDiff) {
return false;
}
}
return true;
}
This function will return true if the array can be rearranged to form an arithmetic progression, and false otherwise.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?