Showing posts with label Exercise. Show all posts
Showing posts with label Exercise. Show all posts

Tuesday, April 7, 2020

[Java][Exerise] Valid Palindrome

Method 1 - work method
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        String cleanStr = s.toLowerCase().replaceAll("[^a-z0-9]","");
        int end = cleanStr.length()-1;
        for(int start=0; start<(cleanStr.length()/2);start++){
            if(cleanStr.charAt(start)!=cleanStr.charAt(end))
                return false;
            end--;
        }
        return true;
    }
}

Method 2 - cleanest method
class Solution {
    public boolean isPalindrome(String s) {
        if(s.length() == 0) return true;
        StringBuilder sb = new StringBuilder(s.toLowerCase().replaceAll("[^a-z0-9]", ""));             
        return sb.toString().equals(sb.reverse().toString());
    }
}


method 3 - work method with replaceAll
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        String cleanStr = s.toLowerCase().replaceAll("[^a-z0-9]","");
        int start = 0;
        int end   = cleanStr.length()-1;
       
        while(start<end){
            if(cleanStr.charAt(start)!=cleanStr.charAt(end)){
                return false;
            }
            end--;
            start++;
        }
        return true;
    }
}

Method 4 - fast method without replaceAll
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        int start = 0;
        int end   = s.length()-1;
       
        while(start<end){
            char startChar = Character.toLowerCase(s.charAt(start));
            char endChar = Character.toLowerCase(s.charAt(end));
           
            if(!Character.isLetterOrDigit(startChar)){
                start++;
                continue;
            }
            if(!Character.isLetterOrDigit(endChar)){
                end--;
                continue;
            }
         if(startChar!=endChar){
                return false;
            }
            end--;
            start++;
        }
        return true;
    }
}


Method 5 - fast method checking with ascii code

From this table we can found the range of 0-9 us 48-57, and a-z are 97-122.
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        int start = 0;
        int end   = s.length()-1;
       
        while(start<end){
            int startChar = (int) Character.toLowerCase(s.charAt(start));
            int endChar   = (int) Character.toLowerCase(s.charAt(end));
           
            if(!((startChar>=48 && startChar<=57)||(startChar>=97 && startChar<=122))){
                start++;
                continue;
            }
            if(!((endChar>=48 && endChar<=57)||(endChar>=97 && endChar<=122))){
                end--;
                continue;
            }
         if(startChar!=endChar){
                return false;
            }
            end--;
            start++;
        }
        return true;
    }
}

Wednesday, April 1, 2020

[Java][Exerise] First Unique Character in a String

Method 1 (28s)
Use LinkedHaspMap Count occurance of Character in String
class Solution {
    public int firstUniqChar(String s) {
        if(s.length()==0) return -1;
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }else{
                map.put(c,1);
            }
        }
        for(Character key: map.keySet()){
            Integer value = map.get(key);
            if(value == 1){
                return s.lastIndexOf(String.valueOf(key));
            }
        }
        return -1;
    }
}
Method 2 (7s)
This method faster than method 1 for 4 time.
class Solution {
    public int firstUniqChar(String s) {
        if(s.length()==0) return -1;
        int[] counts = new int[26];
        for(int i=0; i<s.length(); i++)
            counts[s.charAt(i)-'a']++;
        for(int i=0; i<s.length(); i++){
            if(counts[s.charAt(i)-'a'] == 1)
                return i;
        }
        return -1;
    }
}

Saturday, March 14, 2020

[Java][Exercise] Valid Anagram


Given two strings s and t, write a function to determine if t is an anagram of s.

Bad method 1
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
       
        ArrayList<Character> chars = new ArrayList<Character>();
        for(char c:s.toCharArray()){
            chars.add(c);
        }
        for(int i=0; i< t.length(); i++){
            int index = chars.indexOf(t.charAt(i));
            if (index >= 0){
                chars.remove(index);
            }
        }
        return chars.isEmpty();
    }
}


Bad method 2 (same effectivity as method 1)
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        for(int i=0; i< t.length(); i++){
            int index = s.indexOf(t.charAt(i));
            if(index>=0){
                s = s.substring(0,index)+s.substring(index+1,s.length());
            }
        }
        return s.isEmpty();
    }
}

Better method
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        StringBuilder sb = new StringBuilder(s);
        for(int i=0; i< t.length(); i++){
            int index = sb.indexOf(Character.toString(t.charAt(i)));
            if(index>=0){
                sb.deleteCharAt(index);
            }
        }
        return sb.length()==0;
    }
}

Good method 1
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        char[] str1 = s.toCharArray();
        char[] str2 = t.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return Arrays.equals(str1, str2);
    }
}

Good methods 2
public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) {
        return false;
    }
    int[] counter = new int[26];
    for (int i = 0; i < s.length(); i++) {
        counter[s.charAt(i) - 'a']++;
        counter[t.charAt(i) - 'a']--;
    }
    for (int count : counter) {
        if (count != 0) {
            return false;
        }
    }
    return true;
}

Thursday, January 16, 2020

[Java][Exercise] Impletment of swap and bubble sort

Swap is a act of exchanging the values of the variables mutually. In this article, logic of swap will be used for exchange 2 values for using in bubble search, it will be used if a number bigger than folowing number.Here is the logic of swap function:
public class Main{
  public static void main(String[] args){
    int a = 9;
    int b = 5;
    int[] c = swap(a,b);
    System.out.println(a+":"+b);
    System.out.println(c[0]+":"+c[1]);
  }
  public static int[] swap(int arg1, int arg2){
    int temp = arg2;
    arg2 = arg1;
    arg1 = temp;
    return new int[]{arg1, arg2};
  }
}
Result:
9:5
5:9

By wiki defination, "bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted." To understand what is bubble sort, let have an example with 5 numbers, right now we have 5 numbers 9,8,7,6,5 in decreasing order, and want to sort them in in increasing order, how can we do that with bubble sort?

We would compare the first pair of 2 numbers (with index 0 and index 1), and swap(excahnge the valueables) them if first value bigger than latter one.and then repeat this action on next pair of 2 numbers (with index 1 and index 2) until the last number in this set is compared. If we using [9,8,7,6,5] as instance, there are 4 passes is required.

First pass
source  :   9,8,7,6,5
1st swap:   8,9,7,6,5
2nd swap:   8,7,9,6,5
3rd swap:   8,7,6,9,5
4th swap:   8,7,6,5,9

Second pass:
source  :   8,7,6,5,9
1st swap:   7,8,6,5,9
2nd swap:   7,6,8,5,9
3rd swap:   7,6,5,8,9

Third pass:
source  :   7,6,5,8,9
1st swap:   6,7,5,8,9
2nd swap:   6,5,7,8,9

Fourth pass:
source  :   6,7,5,8,9
1st swap:   5,6,7,8,9

The first for-loop is the passes for comparing each number item in source array.The second for-loop is for comparing each number item in a pass. Swap logic would applied in script inside these 2 for-loop to do in-place sorting:
public class Main{
  public static void main(String[] args){
    int[] arr = new int[]{9,8,7,6,5};
    System.out.println(Arrays.toString(bubbleSort(arr)));
  }
  public static int[] bubbleSort(int[] arr){
    for(int count=arr.length;1<count;count--){
      for(int i=1;i<arr.length;i++){
        if(arr[i-1]>arr[i]){
          int temp = arr[i-1];
          arr[i-1] = arr[i];
          arr[i] = temp;
          count++;
        }
      }
    }
    return arr;
  }
}
input : [9,8,7,6,5]
output: [5,6,7,8,9]

Reference

https://4xsc.com/java-swap/
https://en.wikipedia.org/wiki/Bubble_sort
https://en.wikipedia.org/wiki/In-place_algorithm
https://en.wikipedia.org/wiki/Swap_(computer_programming)

Wednesday, March 6, 2019

[Java][Resolved] Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

Answer:

loop all non-zero numbers fill remain items with zero:
public void moveZeroes(int[] nums) {
  int i=0;
  for(int num: nums){
    if(num !=){
      nums[i++] = num;
    }
  }
  while(i<nums.length){
    nums[i++]=0;
  }
}

Wednesday, November 14, 2018

[JavaScript][Exercise] Remove buttons by clicking button

An image gallery is a set of images with corresponding remove buttons. This is the HTML code for a gallery with two images:

<div class="image">
  <img src="https://goo.gl/kjzfbE" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="https://goo.gl/d2JncW" alt="Second">
  <button class="remove">X</button>
</div>
Implement the setup function that registers a click event handler and implements the following logic: When the button of class remove is clicked, its parent <div> element should be removed from the gallery.

For example, after the first image has been removed from the gallery above, it's HTML code should look like this:

<div class="image">
  <img src="https://goo.gl/d2JncW" alt="Second">
  <button class="remove">X</button>
</div>
  
Referenced answer
Firstly we need to know how many image in gallery. Use a for-loop to add eventListener to related DOM, if click event is trigger, delete parentNode.
<html>
<body>
</body>
<script>
function setup() {
  var len = document.getElementsByClassName("remove").length;
  for(var i=0;i<len;i++){
      document.getElementsByClassName("remove")[i].addEventListener("click",function(){
        this.parentNode.remove();
      });
  }

}

// Example case.
document.body.innerHTML = `
<div class="image">
  <img src="https://goo.gl/kjzfbE" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="https://goo.gl/d2JncW" alt="Second">
  <button class="remove">X</button>
</div>`;

setup();
console.log(document.body.innerHTML);
</script>
</html>
Beware this not work:
document.getElementsByClassName("remove")[i].click(function(){
    this.parentNode.remove();
});

Reference

https://stackoverflow.com/questions/40144638/how-to-remove-the-div-that-a-button-is-contained-in-when-the-button-is-clicked

Saturday, September 15, 2018

[Java][Exerise] Palindrome

Anonymous A palindrome is a word that reads the same backward or forward.

Write a function that checks if a given word is a palindrome. Character case should be ignored.

For example, isPalindrome("Deleveled") should return true as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward.

Reference answer

public class Palindrome {
    public static boolean isPalindrome(String word) {
        word = word.toLowerCase();
        int len = (int) Math.floor(word.length()/2);
        for(int i=0;i<len;i++){
            if(word.charAt(i)!=word.charAt(word.length()-i-1)){
                return false;
            }
        }
        return true;
    }
   
    public static void main(String[] args) {
        System.out.println(Palindrome.isPalindrome("Deleveled"));
    }
}

[Java][Exercise] Three-node binary tree

A three-node binary tree.Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree.

Write a function that, efficiently with respect to time used, checks if a given binary search tree contains a given value.

For example, for the following tree:

n1 (Value: 1, Left: null, Right: null)
n2 (Value: 2, Left: n1, Right: n3)
n3 (Value: 3, Left: null, Right: null)
Call to contains(n2, 3) should return true since a tree with root at n2 contains number 3.

Reference answer

class Node {
    public int value;
    public Node left, right;

    public Node(int value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}


public class BinarySearchTree {
    public static boolean contains(Node root, int value) {
       if(root.value == value)
           return true;

       else if(value < root.value){
           if(root.left == null)
               return false;
           return contains(root.left, value);
       }
       else if(value > root.value){
           if(root.right == null)
               return false;
           return contains(root.right, value);
       }

        return false;
    }
   
    public static void main(String[] args) {
        Node n1 = new Node(1, null, null);
        Node n3 = new Node(3, null, null);
        Node n2 = new Node(2, n1, n3);
       
        System.out.println(contains(n2, 3));
    }
}

Reference:
https://stackoverflow.com/questions/40095082/java-including-bst

Sunday, July 15, 2018

[JavaScript][Exercise] check membershipID digit.

Your company assigns each customer a membership ID, and you are implementing a check digit for those IDs.

The check digit should be calculated by adding up all digits in each membership ID. If the result of the sum is a number with more than a single digit, another iteration is required, and the digits of the result also should be added together. This process should repeat until a single-digit number is calculated.

For example, for the membership ID "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7, would be the check digit.

Reference answer

To get 100% marks, you need to fit 4 requirements:
  1. Fit example case (55555)
  2. Single iteration required
  3. Two iterations required
  4. Multiple iterations required
 We need recursive function:
function createCheckDigit(membershipId) {
  var sum = 0;
  for(var i=0;i<membershipId.toString().length;i++){
    sum += parseInt(membershipId.toString()[i]);
  }
  if(sum.toString().length>1){
    sum = createCheckDigit(sum);
  }
  return sum;
}

Monday, March 19, 2018

[Java][Answer] CodingBat Array-2 > sum67()

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4

Answer 1:
public int sum67(int[] nums) {
  int sum  = 0;
  boolean stop = false;
  for(int i=0;i<nums.length;i++){
      if(nums[i]==6) stop=true;
      if(!stop)sum += nums[i];
      if(nums[i]==7) stop=false;    
  }
  return sum;
}

Answer 2:
public int sum67(int[] nums) {
  int sum = 0;
  boolean stop = false;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 6)
      stop = true;
    if (stop == false)
      sum += nums[i];
    if (nums[i] == 7 && stop == true)
      stop = false;
  }
  return sum;
}

Reference
http://www.javaproblems.com/2013/11/java-array-2-sum67-codingbat-solution.html

Thursday, February 22, 2018

[JavaScript][Exercise] Fix the bugs in the registerHandlers function


Fix the bugs in the registerHandlers function. An alert should display anchor's zero-based index within a document instead of following the link.

For example, in the document below, the alert should display "2" when Google anchor is clicked since it is the third anchor element in the document and its zero-based index is 2.
<body>
  In my life, I used the following web search engines:<br/>
  <a href="//www.yahoo.com">Yahoo!</a><br/>
  <a href="//www.altavista.com">AltaVista</a><br/>
  <a href="//www.google.com">Google</a><br/>
</body> 

Reference answer

We can't edit html code in this question! So we need to amend the html code by JavaScript, Set an attribute to store index of a tag, and call it in click event.
<html>
<body>
  In my life, I used the following web search engines:<br/>
  <a href="//www.yahoo.com">Yahoo!</a><br/>
  <a href="//www.altavista.com">AltaVista</a><br/>
  <a href="//www.google.com">Google</a><br/>
</body>
<script>
registerHandlers();
function registerHandlers() {
  var as = document.getElementsByTagName('a');
  for (var i = 0; i < as.length; i++) {
    as[i].setAttribute('data-index', i);
    as[i].onclick = function() {
      alert(this.getAttribute("data-index"));
      return false;
    }
  }
}
</script>
</html>
Reference
https://stackoverflow.com/questions/31632679/javascript-get-the-right-zero-based-index-of-clicked-link

Tuesday, February 20, 2018

[JavaScript][Exercise] Function appendChildren should add a new child div to each existing div.


Function appendChildren should add a new child div to each existing div. New divs should be decorated by calling decorateDiv.
For example, after appendChildren is executed, the following divs:
<div id="a">
  <div id="b">
  </div>
</div>
should take the following form (assuming decorateDiv does nothing):
<div id="a">
  <div id="b">
    <div></div>
  </div>
  <div></div>
</div>
The code below should do the job, but for some reason it goes into an infinite loop. Fix the bugs.

Reference answer

This is a question about manipulate dom element, document.getElementsByTagName("div"); return live DOM, if you use document.createElement("div") create more DOM element, it increase value stored in allDivs and create an infinity for-loop. So you need to use a variable to store amount of your div live DOM element before you append any child.
<html>
<body>
</body>
<script>
function appendChildren(decorateDivFunction) {
  var allDivs = document.getElementsByTagName("div");
  var len = allDivs.length;

  for (var i = 0; i < len; i++) {
    var newDiv = document.createElement("div");
    decorateDivFunction(newDiv);
    allDivs[i].appendChild(newDiv);
  }
}

// Example case.
document.body.innerHTML = `
<div id="a">
  <div id="b">
  </div>
</div>`;

appendChildren(function(div) {});
console.log(document.body.innerHTML);
</script>
</html>

Reference
https://stackoverflow.com/questions/29605980/appending-child-div-to-each-div-with-for-loop

Thursday, February 8, 2018

[Java][Exercise] CodingBat equalIsNot answer

Question

Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in the string (case sensitive).

equalIsNot("This is not") → false
equalIsNot("This is notnot") → true
equalIsNot("noisxxnotyynotxisi") → true

Expected result

 Solution

public boolean equalIsNot(String str) {
  return getAmount(str,"is") == getAmount(str,"not");
}

private int getAmount(String base, String occu){
  int amount = 0;
  int lastInd = 0;
  while(lastInd!=-1){
    lastInd = base.indexOf(occu,lastInd);
    if(lastInd!=-1){
      lastInd += occu.length();
      amount++;
    }
  }
  return amount;
}

Reference

https://stackoverflow.com/questions/767759/occurrences-of-substring-in-a-string
http://codingbat.com/prob/p141736

Friday, January 19, 2018

[Java][Answer] CodingBat Array-1 > plusTwo()

Given 2 int arrays, each length 2, return a new array length 4 containing all their elements.

plusTwo([1, 2], [3, 4]) → [1, 2, 3, 4]
plusTwo([4, 4], [2, 2]) → [4, 4, 2, 2]
plusTwo([9, 2], [3, 4]) → [9, 2, 3, 4]

Answer 1:

public int[] plusTwo(int[] a, int[] b) {
  return new int[]{a[0],a[1],b[0],b[1]};
}

Answer 2:

public int[] plusTwo(int[] a, int[] b) {
  int[] myArray = new int[4];
  myArray[0] = a[0];
  myArray[1] = a[1];
  myArray[2] = b[0];
  myArray[3] = b[1];
 
  return myArray;
}

Reference

http://www.javaproblems.com/2013/11/java-array-1-plustwo-codingbat-solution.html

Thursday, December 21, 2017

[JavaScript][Exercise] converts Date format

Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.

For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.

Reference answer 1:

function formatDate(userDate) {
  var temp = userDate.split("/");
  if (temp[0].length < 2) temp[0] = '0' + temp[0];
  if (temp[1].length < 2) temp[1] = '0' + temp[1];
  return temp[2]+temp[0]+temp[1];
}

console.log(formatDate("12/31/2014"));

Reference answer 2:

function formatDate(userDate) {
    var d = new Date(userDate),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join("");
}

console.log(formatDate("12/31/2014"));

Reference

https://stackoverflow.com/questions/23593052/format-javascript-date-to-yyyy-mm-dd

Friday, December 15, 2017

[JavaScript][Exercise] Throw Error if without argument.

Implement the ensure function so that it throws an error if called without arguments or the argument is undefined. Otherwise it should return the given value.

Reference answer

function ensure(value) {
  if(value === undefined) throw new Error('no arguments');
  return value;
}

Reference 

https://stackoverflow.com/questions/44874410/javascript-function-should-throw-an-error-if-called-without-arguments-or-an-argu

Friday, May 19, 2017

[Java][Answer] Array-1 > biggerTwo()

Start with 2 int arrays, a and b, each length 2. Consider the sum of the values in each array. Return the array which has the largest sum. In event of a tie, return a.

biggerTwo([1, 2], [3, 4]) → [3, 4]
biggerTwo([3, 4], [1, 2]) → [3, 4]
biggerTwo([1, 1], [1, 2]) → [1, 2]

Answer 1:

public int[] biggerTwo(int[] a, int[] b) {
  if(a[0]+a[1] < b[0]+b[1]) return b;
  return a;
}

Answer 2:

public int[] biggerTwo(int[] a, int[] b) {
  if (b[1] + b[0] > a[1] + a[0])
  return b;
  else
  return a;
}

Reference

http://www.javaproblems.com/2012/12/coding-bat-java-array-1-biggertwo.html

Monday, April 24, 2017

[Java][Exerice] CodingBat Array-2 > tenRun answer

For each multiple of 10 in the given array, change all the values following it to be that multiple of 10, until encountering another multiple of 10. So {2, 10, 3, 4, 20, 5} yields {2, 10, 10, 10, 20, 20}.

tenRun([2, 10, 3, 4, 20, 5]) → [2, 10, 10, 10, 20, 20]
tenRun([10, 1, 20, 2]) → [10, 10, 20, 20]
tenRun([10, 1, 9, 20]) → [10, 10, 10, 20]

Solution 1:
public int[] tenRun(int[] nums) {
  boolean ten = false;
  int tmp = 0;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] % 10 == 0) {
      tmp = nums[i];
      ten = true;
    }
    else if (nums[i] % 10 != 0 && ten) {
      nums[i] = tmp;
    }
  }
  return nums;
}
Solution 2:
 public int[] tenRun(int[] nums) {
  boolean ten = false;
  int temp = 0;
  for(int i=0;i<nums.length;i++){
    if(nums[i]%10==0){
      ten = true;
      temp = nums[i];
    }else{
      if(ten) nums[i] =temp;
    }
  }
  return nums;
}

Reference:
http://www.javaproblems.com/2013/11/java-array-2-tenrun-codingbat-solution.html

Wednesday, April 19, 2017

[Java][Answer] CodingBat Array-1 > frontPiece()

Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present.

frontPiece([1, 2, 3]) → [1, 2]
frontPiece([1, 2]) → [1, 2]
frontPiece([1]) → [1]

Answer 1:
public int[] frontPiece(int[] nums) {
  if(nums.length<2) return nums;
  return new int[]{nums[0],nums[1]};
}
Answer 2:
public int[] frontPiece(int[] nums) {
  if (nums.length == 1)
  return new int[] {nums[0]};
  else if (nums.length == 0)
  return new int[] {};
  else
  return new int[] {nums[0],nums[1]};
}

Reference
http://www.javaproblems.com/2012/12/coding-bat-java-array-1-frontpiece.html

[Java][Answer] CodingBat Array-1 > maxTriple()

Given an array of ints of odd length, look at the first, last, and middle values in the array and return the largest. The array length will be a least 1.

maxTriple([1, 2, 3]) → 3
maxTriple([1, 5, 3]) → 5
maxTriple([5, 2, 3]) → 5

Answer 1:
public int maxTriple(int[] nums) {
  if(nums.length == 1) return nums[0];
  if(nums.length == 2) return Math.max(nums[0],nums[1]);
  return Math.max(Math.max(nums[0],nums[nums.length/2]),
                  Math.max(nums[nums.length/2],nums[nums.length-1])
                  );
}
Answer 2:
public int maxTriple(int[] nums) {
  int result = 0;
  int a = nums[0];
  int b= nums[((nums.length+1)/2) -1;
  int c = nums[nums.length -1];
 
  if (a>b && a>c)
  result = a;
    if (b>a && b>c)
  result = b;
    if (c>a && c>b)
  result = c;
  return result;
  }

Reference
http://www.javaproblems.com/2012/12/coding-bat-java-array-1-maxtriple.html