Java > Array-1 > maxEnd3 (CodingBat Solution)

Problem:

Given an array of ints length 3, figure out which is larger between the first and last elements in the array, and set all the other elements to be that value. Return the changed array.

maxEnd3({1, 2, 3}) → {3, 3, 3}
maxEnd3({11, 5, 9}) → {11, 11, 11}
maxEnd3({2, 11, 3}) → {3, 3, 3}


Solution:

public int[] maxEnd3(int[] nums) {
  int larger = Math.max(nums[0], nums[2]);
  
  nums[0] = larger;
  nums[1] = larger;
  nums[2] = larger;
  return nums;
}


9 comments :

  1. public int[] maxEnd3(int[]nums){
    int z = Math.max(nums[0], nums[nums.length-1]);
    for(int x = 0; x<nums.length; x++)
    nums[x] = z;
    return nums;
    }

    ReplyDelete
  2. int max = values[0];
    for (int index = 0 ; index < values.length ; index++)
    {
    max = Math.max(max, values[index]);
    }

    ReplyDelete
  3. sorry its this one

    int max = Math.max(nums[0], nums[2]);
    int arr[] = {max, max, max};
    return arr;

    ReplyDelete
    Replies
    1. Sure, but it says to return the "changed" array. You modify it in-place.

      Delete
  4. public int[] maxEnd3(int[] nums) {
    return new int[]{Math.max(nums[0], nums[2]), Math.max(nums[0], nums[2]), Math.max(nums[0], nums[2])};
    }

    ReplyDelete
  5. public int[] maxEnd3(int[] nums) {
    int max = Math.max(nums[0], nums[2]);
    return new int[]{max, max, max};
    }

    ReplyDelete
  6. int max = Math.max(nums[0], nums[2]);
    nums[0] = nums[1] = nums[2] = max;
    return nums;

    ReplyDelete
  7. public int[] maxEnd3(int[] nums) {
    int max =0;
    if(nums[0]>nums[nums.length-1]){
    max=nums[0];
    }else{
    max=nums[nums.length-1];
    }

    for(int i=0;i<nums.length;i++){
    nums[i]=max;
    }
    return nums;
    }

    ReplyDelete
  8. public int[] maxEnd3(int[] nums) {
    if(nums[0]>nums[2])
    {
    int a[]={(nums[0]),(nums[0]),(nums[0])};
    return a;
    }
    else
    {
    int b[]={(nums[2]),(nums[2]),(nums[2])};
    return b;
    }
    }

    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