Codingbat Java-Array-3>maxSpan (Click Here For The Problem):
Solution code:
public int maxSpan(int[] nums) {
int largestSpan = -1;
for(int i=0; i<nums.length ; i++){
for(int j=nums.length-1; j>=i ; j--){
if(nums[i] == nums[j]){
if((j-i) > largestSpan){
largestSpan = (j-i);
}
}
}
}
return largestSpan+1;
}
int largestSpan = -1;
for(int i=0; i<nums.length ; i++){
for(int j=nums.length-1; j>=i ; j--){
if(nums[i] == nums[j]){
if((j-i) > largestSpan){
largestSpan = (j-i);
}
}
}
}
return largestSpan+1;
}
Logic behind the code :
1] Take a variable whose value indicates the largest span and which we will return at the end as an answer.
2] As we don't know what is it's value initially, so let us assume it as -1.
3] We will now traverse the array from left picking each and every element using a loop and will traverse from rightmost end of the array using another loop.
4] In this way we will check the rightmost occurrence of the element.
5] Now we will subtract the index of the element from the rightmost occurrence of the element.
6] As the array indexing starts from 0, we have to add 1 to our answer.
Solution code:
public int countClumps(int[] nums) {
int count = 0;
boolean gotit = false;
for(int i=0; i<nums.length-1; i++){
if(nums[i] == nums[i+1] && (gotit==false)){
count++;
gotit = true;
}
if(nums[i] != nums[i+1]){
gotit = false;
}
}
return count;
}