Java > Warmup-2 > has271 (CodingBat Solution)

Problem:

Given an array of ints, return true if it contains a 2, 7, 1 pattern -- a value, followed by the value plus 5, followed by the value minus 1. Additionally the 271 counts even if the "1" differs by 2 or less from the correct value.

has271({1, 2, 7, 1}) → true
has271({1, 2, 8, 1}) → false
has271({2, 7, 1}) → true


Solution:

public boolean has271(int[] nums) {
  int len = nums.length;

  for (int i = 0; i < nums.length - 1; i++) {   
    if (i+2 <= nums.length - 1){
      int j = Math.abs(nums[i] - 1);  
      int k = Math.abs(j - nums[i+2]);         
      if(nums[i+1] == nums[i]+5 && k <= 2)
        return true;      
    }    
          
  } return false;
}


2 comments :

  1. not understand, plz share any another solution.

    ReplyDelete
    Replies
    1. take the last example and dry run it is easy

      Delete

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