Deepak Deepak - 4 months ago 132
Java Question

Find the largest span between the same number in an array



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 6>4 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
}

Answer

I see the following problems with your attempt:

  • Your count is completely wrong. You can instead calculate count from i and j: j - i + 1

  • You're overriding maxcount as soon as you get any span, so you're going to end up with the last span, not the maximum span. Fix it by going maxspan = Math.max(maxspan, count);.

  • You can remove the line int number = nums[i]; as you never use number.

  • Remove the +1 in the returnmaxspan+1;` if you follow my tips above.

  • Initial maxspan should be 1 if there are any values in the array, but 0 if the array is empty.

That should help you get it working. Note that you can do this in a single pass of the array, but that's probably stretching it too far for you. Concentrate on getting your code to work before considering efficiency.