This question is catergorized as a Harder array question.
Consider the leftmost and rightmost 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. Returns the largest span found in the given array. (Efficiency is not a priority.)
maxSpan({1, 2, 1, 1, 3}) → 4
maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6
maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6
1: public int maxSpan(int[] nums) {2: int lspan=0; String snum="";3: // assign nums in to a srting4: for(int i=0;i<nums.length;i++){5: snum+= String.valueOf(nums[i]);6: }7: for(int j=0,span=0;j<snum.length();j++){8: span=snum.lastIndexOf(snum.charAt(j)) - snum.indexOf(snum.charAt(j))+1;9: //span is always larger than 010: if(span>lspan)11: lspan=span;12: }13: return lspan;14: }
..