int num_distinct(int a[], int n)
{
int i, k, j, count=0;
int max = a[0];
for (i = 1; i < n; i++) {
if (max < a[i]) {
max = a[i];
}
}
for (k = 0; k < n; ++k) {
for (j = 0; j < n; ++j) {
if (a[j] == max) {
++count;
--max;
break;
}
}
}
return (count);
}
What i tried to do is find the max in the array and compare that to the rest of the elements in the array. It works, but when the array skips a number i.e. (1,2,2,5,6,7,8) <-- it skipped 3 and 4. My code will only count 8,7,6,5 which returns 4 unique numbers.
maxupon finding a match, which you will not do when you have a hole in your sequence. Ex: your test vector will find 8, 7, 6, and 5, but as there is no 4maxis never adjusted to look for3,2, or1, and the double-loop eventually terminates with a sum count of the four items you found.