'Find the max number function

I had this interview Q, how would you solve this?

Given the three integers, x,y and z, convert x to y by repeatedly performing these operations: adding 1 to x or subtracting 1 from x. A Maximum of z operations can be performed to reach y, and, if necessary, all operations may be the same. As the operations applied. keep track of the maximum vale that x achieves. The goal is to create the highest possible value of x somewhere along the way while arriving at the largest value within the z operations

The maximum achievable value of x is 6. Because maximum of 4 moves are available, 1 can be added twice and subtracted twice to arrive back at 4. Performing 0 or 2 moves would still arrive at the target value but would have maximum of 4 and 5, respectively

findMaxNum has the following parameters

int x : starting value int y: the target value int z: the maximum number of steps

Returns: int: the maximum integer which can be made from x while converting x to y in most z steps; if cannot be converted to y after the most z steps, return -1

function findMaxNum(x,y,z){

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source