Check if array elements are consecutive
Input: {5,4,1,2,3}
Output: yes
Explanation: Max element is 5 and min element id 1, Array contains all elements from 1 to 5
Input: {2,1,0,-3,-2,-1}
Output: yes
Explanation: Array contains elements from -3 to 2.
Concept used:
If the array elements are consecutive and distinct then the array is in AP.
So we compare array sum with AP sum.
ap_sum = n/2 * [2a +(n-1)*d] where d = 1, since elements are consecutive.
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = {5, 4, 2, 1, 3};
int n = a.length;
int sum = 0;
boolean result = false;
int first = a[0];
for(int i=1; i<n; i++){
if(a[i]<first)
first = a[i];
}
int apSum = (n * (2*first + (n-1)) / 2);
for(int i=0; i<n; i++){
sum += a[i];
}
if(apSum == sum)
result = true;
System.out.println("apsum "+apSum+" array sum "+sum);
if(result)
System.out.print("Yes");
else
System.out.print("No");
}
}
Output:
apsum 15 array sum 15
Yes
Comments
Post a Comment