If the array is sorted,
count = 1;
for (i = 1 to n-1){
if(a[i-1] == a[i]){
count = count + 1;
}else if(a[i-1] + 1 == a[i]){
count of sub arrays for a[i-1] = count;
count = count + 1;
}else{
count of sub arrays for a[i-1] = count;
count = 1;
}
}
count of sub arrays for a[n-1] = count;
If the array is not sorted,
Assumption 3:If the array is like {3,1,2,3} then #sub arrays for 3 is 3
aMin = min(a);//O(n)
aMax = max(a);
len = (aMax - aMin + 1);
create array b of size len;
for (j = 0 to len-1){
b[j] = 0;
}
count = 1;
for (i = 1 to n-1){
if(a[i-1] == a[i]){
count = count + 1;
}else if(a[i-1] + 1 == a[i]){
if(b[a[i-1] - aMin] < count){
b[a[i-1] - aMin] = count;
}
count = count + 1;
}else{
if(b[a[i-1] - aMin] < count){
b[a[i-1] - aMin] = count;
}
count = 1;
}
}
if(b[a[n-1] - aMin] < count){
b[a[n-1] - aMin] = count;
}
for (i = 0 to n-1){
count of sub arrays for a[i] = b[a[i] - aMin];
}
This will work even if the array contains negative integers
If Assumption 3 fails according to your problem, and it is like,
Assumption 4:If the array is like {3,1,2,3} then #sub arrays for 3 is 4
{3}, {1,2,3}, {2,3}, {3}
Modify the above code by replacing
if(b[a[i-1] - aMin] < count){
b[a[i-1] - aMin] = count;
}
with this
b[a[i-1] - aMin] = b[a[i-1] - aMin] + count;