Skip to content

Commit d79d74c

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 12.8 MB (42.12%)
1 parent 0e9f82f commit d79d74c

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>A sequence of numbers is called an <strong>arithmetic progression</strong> if the difference between any two consecutive elements is the same.</p>
2+
3+
<p>Given an array of numbers <code>arr</code>, return <code>true</code> <em>if the array can be rearranged to form an <strong>arithmetic progression</strong>. Otherwise, return</em> <code>false</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> arr = [3,5,1]
10+
<strong>Output:</strong> true
11+
<strong>Explanation: </strong>We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> arr = [1,2,4]
18+
<strong>Output:</strong> false
19+
<strong>Explanation: </strong>There is no way to reorder the elements to obtain an arithmetic progression.
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li><code>2 &lt;= arr.length &lt;= 1000</code></li>
27+
<li><code>-10<sup>6</sup> &lt;= arr[i] &lt;= 10<sup>6</sup></code></li>
28+
</ul>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution {
2+
public:
3+
bool canMakeArithmeticProgression(vector<int>& arr) {
4+
int n = arr.size();
5+
sort(arr.begin(), arr.end());
6+
int diff = arr[1] - arr[0];
7+
for (int i=1; i<n; i++) {
8+
if (arr[i] - arr[i-1] != diff) return false;
9+
}
10+
return true;
11+
}
12+
};

0 commit comments

Comments
 (0)