Question:
Say that a "clump" in an array is a series of 2 or more adjacent elements of the same value. Return the number of clumps in the given array.
countClumps({1, 2, 2, 3, 4, 4}) → 2
countClumps({1, 1, 2, 1, 1}) → 2
countClumps({1, 1, 1, 1, 1}) → 1
Source
The method is pretty straightforward we start with checking every number of the array if it is same adjacent value. if found clump variable will be incremented and finally returned as the number of clumps, we increment the iterator(i) to make sure it doesnt check the same value twice.
public int countClumps(int[] nums) {
int clump=0;
for(int i=0; i<nums.length;i++){
if(i+1<nums.length && nums[i+1]==nums[i]){
clump++;
while(i+1<nums.length && nums[i+1]==nums[i]){
i++;
}
}
}
return clump;
}