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; }
public int maxTriple(int[] nums) {
ReplyDeletereturn Math.max(nums[0], Math.max(nums[(nums.length - 1) / 2], nums[nums.length - 1]));
}
return Math.max(nums[0], Math.max(nums[nums.length/2],nums[nums.length-1])); --> middle (-1) redundant
Deletepublic int maxTriple(int[] nums) {
ReplyDeletereturn Math.max(nums[0], Math.max(nums[(nums.length - 1) / 2], nums[nums.length - 1]));
}
this one see to understand
ReplyDeleteint 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];
public int maxTriple(int[] nums) {
ReplyDeleteint 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()
public int maxTriple(int[] nums) {
ReplyDeleteint 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;
}
d=(a>b)?(a>c?a:c):(b>c?b:c);
Deletepublic int maxTriple(int[] nums) {
ReplyDeleteint largest=Math.max(nums[0], nums[nums.length-1]);
largest=Math.max(largest,nums[nums.length/2]);
return largest;
}