Thursday, October 2, 2014

ZeroMax

Ques: Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.

Ans:
 public static int[] zeroMax(int[] nums) {
 int maxoddtrval = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                for (int j = i + 1; j < nums.length; j++) {
                    if(nums[j]%2==1){
                        maxoddtrval=nums[j];
                        for(int k=j+1;k<nums.length;k++){
                            if(nums[k]>maxoddtrval){
                                maxoddtrval=nums[k];
                                break;
                            }
                        }
//swap the max identified value with zero
                        nums[i]=maxoddtrval;
                        break;
                    }
                }

              
            }
        }
        return nums;
}

No comments:

Post a Comment