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) { if (nums[0] >= nums[nums.length-1]) { nums[0] = nums[0]; nums[1] = nums[0]; nums[2] = nums[0]; } else if (nums[0] <= nums[nums.length-1]) { nums[0] = nums[nums.length-1]; nums[1] = nums[nums.length-1]; nums[2] = nums[nums.length-1]; } return new int[] { nums[0],nums[1],nums[2]}; }
If you find this solution hard you might be looking for a normal and easy (non-recursive) solution here.
in line 2 declaring integer index looks odd and shouldbe removed from code i guess
ReplyDeleteI agree, it's a code-typo :). Thanks for noticing, I will remove it.
DeleteDo you really need to say nums[0] = nums[0]; and nums[2] = nums[nums.length-1]; ?
ReplyDeleteThose indexes are not going to change anyway, so removing those two lines of code wouldn't change the correctness of your solution.
Stelios
CAN WE DO THIS
ReplyDeletepublic int[] maxEnd3(int[] nums) {
if(nums[0]>nums[nums.length-1])
return new int nums[]{nums[0] ,nums[0] ,nums[0]};
else
return new int nums[]{nums[nums.length-1] ,nums[nums.length-1] ,nums[nums.length-1]};
}
public int[] maxEnd3(int[] nums) {
ReplyDeleteint max=nums[0]>nums[nums.length-1]?nums[0]:nums[nums.length-1];
return new int[]{max,max,max};
}
int x = Math.max(nums[0], nums[2]);
ReplyDeletereturn new int[] {x,x,x};
why we wrote it new int?
ReplyDeletepublic int[] maxEnd3(int[] nums) {
ReplyDeleteint max = Math.max(nums[0], nums[2]);
return new int[] { max, max, max };
}
I loved your solution.
DeleteBest solution yet!
Deletepublic int[] maxEnd3(int[] nums) {
ReplyDeleteint[] myArr = new int[3];
if(nums[0]>=nums[2]){
myArr[0]=nums[0];
myArr[1]=nums[0];
myArr[2]=nums[0];
}else if(nums[0]<nums[2]){
myArr[0]=nums[2];
myArr[1]=nums[2];
myArr[2]=nums[2];
}
return myArr;
}
public int[] maxEnd3(int[] nums) {
ReplyDeleteif(nums[0]>nums[2])
return new int [] {nums[0],nums[0],nums[0]};
else if(nums[2]>nums[0])
return new int [] {nums[2],nums[2],nums[2]};
else if(nums[0]==nums[2])
return new int [] {nums[2],nums[2],nums[2]};
else return new int [] {nums[0],nums[1],nums[2]};
}
public int[] maxEnd3(int[] nums) {
ReplyDeleteint max = Math.max(nums[0], nums[nums.length-1]);
for(int i = 0 ; i < nums.length ; i++){
nums[i] = max;
}
return nums;
}
int res[] = new int[nums.length];
ReplyDeleteint max = 0;
if(nums[0] > nums[nums.length-1] ){
max = nums[0];
}else{
max = nums[nums.length-1];
}
for(i=0; i < res.length; i++){
res[i]= max;
}
return res;
public int[] maxEnd3(int[] nums) {
ReplyDeleteif (nums[0]>nums[2])
return (new int [] {nums[0],nums[0],nums[0]});
else
return (new int [] {nums[2],nums[2],nums[2]});
}