|
| 1 | +package com.rampatra.arrays; |
| 2 | + |
| 3 | +import com.sun.tools.javac.util.Assert; |
| 4 | + |
| 5 | +/** |
| 6 | + * Consider the leftmost and rightmost appearances of some value in an array. We'll say that the "span" is the |
| 7 | + * number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found |
| 8 | + * in the given array. |
| 9 | + * <p> |
| 10 | + * Examples: |
| 11 | + * maxSpan([1, 2, 1, 1, 3]) → 4 |
| 12 | + * maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6 |
| 13 | + * maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6 |
| 14 | + * <p> |
| 15 | + * Level: Easy |
| 16 | + * |
| 17 | + * @author rampatra |
| 18 | + * @link https://codingbat.com/prob/p189576 |
| 19 | + * @since 2019-01-23 |
| 20 | + */ |
| 21 | +public class MaxSpan { |
| 22 | + |
| 23 | + public static int maxSpan(int[] nums) { |
| 24 | + if (nums.length == 0) return 0; |
| 25 | + int largestSpan = 1; |
| 26 | + for (int i = 0; i < nums.length; i++) { |
| 27 | + for (int j = nums.length - 1; j > i; j--) { |
| 28 | + if (nums[i] == nums[j]) { |
| 29 | + if (j - i + 1 > largestSpan) { |
| 30 | + largestSpan = j - i + 1; |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + return largestSpan; |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) { |
| 39 | + Assert.check(maxSpan(new int[]{1, 2, 1, 1, 3}) == 4); |
| 40 | + Assert.check(maxSpan(new int[]{1, 4, 2, 1, 4, 1, 4}) == 6); |
| 41 | + Assert.check(maxSpan(new int[]{1, 4, 2, 1, 4, 4, 4}) == 6); |
| 42 | + Assert.check(maxSpan(new int[]{1}) == 1); |
| 43 | + Assert.check(maxSpan(new int[]{}) == 0); |
| 44 | + } |
| 45 | +} |
0 commit comments