Saturday, February 6, 2016

maxSpan --- Answer to the practice problem of coding bat.

The code below is my answer toward the practice problem of coding bat; http://codingbat.com/prob/p189576 .
I know my code is ugly... But it works anyway.

public int maxSpan(int[] nums) {
  if(nums.length == 0){
    return 0;
  }

  int[] counter = new int[nums.length];

  for(int i = 0; i <= nums.length-1; i++){
    for(int j = 0; j <= nums.length-1; j++){
      if(nums[i] == nums[j]){
        counter[i]++;
      }
    }
  }

  int biggest = 0;
  int arrayNumMin = 0;
  int arrayNumMax = 0;

  for(int k = 0; k <= counter.length-1; k++){
    if(biggest < counter[k]){
      biggest = counter[k];
      arrayNumMin = k;
    }
  }

  for(int l = 0; l <= counter.length-1; l++){
    if(nums[l] == nums[arrayNumMin]){
      arrayNumMax = l;
    }
  }

  return arrayNumMax - arrayNumMin + 1;
}