Java > AP-1 > scoresClump (CodingBat Solution)

Problem:

Given an array of scores sorted in increasing order, return true if the array contains 3 adjacent scores that differ from each other by at most 2, such as with {3, 4, 5} or {3, 5, 5}.

scoresClump({3, 4, 5}) → true
scoresClump({3, 4, 6}) → false
scoresClump({1, 3, 5, 5}) → true


Solution:

public boolean scoresClump(int[] scores) {
  if (scores.length < 3)
    return false;
  
  for (int i = 0; i < scores.length-2; i++) {
    if (scores[i+2] - scores[i+1] <= 2 && scores[i+2] - scores[i] <= 2)
      return true;
  }
  return false;
}


5 comments :

  1. Couldn't you take out the "if (scores.length < 3) return false;" since if the length is less than 3, the "if" statement in the loop would never execute and thus end up hitting the final "return false;"
    Also, the array is in ascending order, so if "scores[i+2]-scores[i] <=2", "scores[i+2]-[i+1]" would automatically be true since the list is sorted.

    ReplyDelete
  2. public boolean scoresClump(int[] scores) {
    for(int i = 0; i < scores.length - 2; i++) {
    if(scores[i+2] - scores[i] <= 2) return true;
    }
    return false;
    }

    ReplyDelete
  3. for(int i=scores.length-1; i>=2; i--){
    if(scores[i] - scores[i-2] <=2) return true;
    }

    return false;

    ReplyDelete
  4. public boolean scoresClump(int[] scores)
    {
    for(int i = 2; i < scores.length; i++)
    {
    if(Math.abs(scores[i-2]-scores[i]) <= 2) return true;
    }

    return false;
    }

    ReplyDelete
  5. public boolean scoresClump(int[] scores) {
    for(int i=0;i<scores.length-2;i++){
    if((scores[i+2])-(scores[i])==2){
    return true;
    }
    }
    return false;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact