Hi Stack People,
Merry Christmas and hope you are in great Spirits,I have a Question in Java-Arrays as shown below.Im stuck up with this struggling to get it rite.
Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Write a **Java Function** that returns the largest span found in the given array.
**Example:
maxSpan({1, 2, 1, 1, 3}) ? 4,answer is 4 coz MaxSpan between 1 to 1 is 4
maxSpan({1, 4, 2, 1, 4, 1, 4}) ? 6,answer is 6 coz MaxSpan between 4 to 4 is 6
maxSpan({1, 4, 2, 1, 4, 4, 4}) ? 6,answer is 6 coz Maxspan between 4 to 4 is 6 which is greater than MaxSpan between 1 and 1 which is 4,Hence 64 answer is 6.
I have the code which is not working,it includes all the Spans for a given element,im unable to find the MaxSpan for a given element.
Please help me out.
Results of the above Program are as shown below
Expected This Run
maxSpan({1, 2, 1, 1, 3}) ? 4 5 X
maxSpan({1, 4, 2, 1, 4, 1, 4}) ? 6 8 X
maxSpan({1, 4, 2, 1, 4, 4, 4}) ? 6 9 X
maxSpan({3, 3, 3}) ? 3 5 X
maxSpan({3, 9, 3}) ? 3 3 OK
maxSpan({3, 9, 9}) ? 2 3 X
maxSpan({3, 9}) ? 1 1 OK
maxSpan({3, 3}) ? 2 3 X
maxSpan({}) ? 0 1 X
maxSpan({1}) ? 1 1 OK
::Code::
public int maxSpan(int[] nums) {
int count=1;//keep an intial count of maxspan=1
int maxspan=0;//initialize maxspan=0
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i] == nums[j]){
//check to see if "i" index contents == "j" index contents
count++; //increment count
maxspan=count; //make maxspan as your final count
int number = nums[i]; //number=actual number for maxspan
}
}
}
return maxspan+1; //return maxspan
}