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 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; }
//How about this
ReplyDeletepublic int maxTriple(int[] nums) {
int middle= nums.length/2;
int compare1= Math.max(nums[0],nums[middle]);
return Math.max(compare1,nums[nums.length-1]);
}
Missing closed bracket on line 4 after the 1.
ReplyDeletepublic int maxTriple(int[] nums) {
ReplyDeleteint temp = 0;
if (nums[0] > nums[(nums.length+1)/2-1])
temp = nums[0];
else
temp = nums[(nums.length+1)/2-1];
if (nums[nums.length-1] > temp)
temp = nums[nums.length-1];
return temp;
}
BEST AND EASIEST SOLUTION, trust me:
ReplyDeletepublic int maxTriple(int[] nums) {
int largest = nums[0];
int mid = nums.length / 2;
int[] largeArray = { nums[0], nums[mid], nums[nums.length-1] };
for(int i = 0; i < largeArray.length; i++){
if(largeArray[i] > largest){
largest = largeArray[i];
}
}
return largest;
}
public int maxTriple(int[] nums) {
ReplyDeleteint first = nums[0];
int middle = nums[(nums.length/2)];
int last = nums[nums.length-1];
int firstMax = Math.max(first,middle);
int finalMax = Math.max(firstMax,last);
return finalMax;
}
the answer currently is wrong
ReplyDeletepublic int maxTriple(int[] nums) {
ReplyDeleteint mid= nums.length/2;
int compare= Math.max(nums[0],nums[mid]);
return Math.max(compare,nums[nums.length-1]);
}
int hiValue = 0;
ReplyDeleteint [] Arr = {nums[0], nums[nums.length/2], nums[nums.length-1]};
for(int i = 0; i < Arr.length; i++)
if(hiValue < Arr[i])
hiValue = Arr[i];
return hiValue;
int first = nums[0];//first
ReplyDeleteint middle = nums[nums.length/2];//middle
int last = nums[nums.length-1];//last
return (first>middle && first>last) ? (first) : (Math.max(middle, last));
Easier to follow :) :
ReplyDeletepublic int maxTriple(int[] nums) {
int first = nums[0];
int middle = nums[nums.length/2];
int end = nums[nums.length-1];
int a = Math.max(first, middle);
int b = Math.max(a, end);
return Math.max(a,b);
}