Java > Array-1 > maxTriple (CodingBat Solution)

Problem:

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


Solution:

public int maxTriple(int[] nums) {
  int largest = Math.max(nums[0], nums[nums.length / 2]);
  largest = Math.max(largest, nums[nums.length-1]);
  return largest;
}


8 comments :

  1. public int maxTriple(int[] nums) {
    return Math.max(nums[0], Math.max(nums[(nums.length - 1) / 2], nums[nums.length - 1]));
    }

    ReplyDelete
    Replies
    1. return Math.max(nums[0], Math.max(nums[nums.length/2],nums[nums.length-1])); --> middle (-1) redundant

      Delete
  2. public int maxTriple(int[] nums) {
    return Math.max(nums[0], Math.max(nums[(nums.length - 1) / 2], nums[nums.length - 1]));
    }

    ReplyDelete
  3. this one see to understand
    int n = nums.length;
    int p=n/2;
    if(nums[0]>nums[p]&&nums[0]>nums[n-1])
    return nums[0];
    if(nums[p]>nums[0]&&nums[p]>nums[n-1])
    return nums[p];
    return nums[n-1];

    ReplyDelete
  4. public int maxTriple(int[] nums) {

    int largest = 0;

    if(nums[0] > nums[nums.length / 2] && nums[0] > nums[nums.length-1]);
    largest = nums[0];

    if(nums[nums.length / 2] > nums[0] && nums[nums.length / 2] > nums[nums.length-1])
    largest = nums[nums.length / 2];

    if(nums[nums.length-1] > nums[0] && nums[nums.length-1] > nums[nums.length / 2])
    largest = nums[nums.length - 1];

    return largest;
    }

    A bit longer with the Math.max()

    ReplyDelete
  5. public int maxTriple(int[] nums) {
    int d=(nums[0]>nums[nums.length/2])?(nums[0]>nums[nums.length-1]?nums[0]:nums[nums.length-1]):(nums[nums.length/2]>nums[nums.length-1]?nums[nums.length/2]:nums[nums.length-1]);
    return d;
    }

    ReplyDelete
  6. public int maxTriple(int[] nums) {
    int largest=Math.max(nums[0], nums[nums.length-1]);
    largest=Math.max(largest,nums[nums.length/2]);
    return largest;
    }

    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