Given an array of numbers
Return
arr
. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.Return
true
if the array can be rearranged to form an arithmetic progression, otherwise, return false
.Example 1:
Input: arr = [3,5,1]
Output: true
Approach
Java
import java.util.Arrays;public class CanMakeArithmeticProgression {public static void main(String[] args) {int[] arr = { 3, 5, 1 };System.out.println(canMakeArithmeticProgression(arr));}static boolean canMakeArithmeticProgression(int[] arr) {Arrays.sort(arr);int diff = arr[0] - arr[1];int flag = 0;int n = arr.length;for (int i = 2; i < n; i++) {if (arr[i - 1] - arr[i] != diff) {flag = 1;break;}}if (flag == 0)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool canMakeArithmeticProgression(vector<int> &arr){sort(arr.begin(), arr.end());int diff = arr[0] - arr[1];int flag = 0;int n = arr.size();for (int i = 2; i < n; i++){if (arr[i - 1] - arr[i] != diff){flag = 1;break;}}if (flag == 0)return true;return false;}int main(){vector<int> arr = {3, 5, 1};if (canMakeArithmeticProgression(arr))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment