Wednesday, April 19, 2017

[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

No comments :

Post a Comment