This is the question from recently CodeJunk Contest, It gives me WA , I try my best but I can’t Figure out how to correct my code.
My approach->> Basically Using Binary search from low =1 to high=m , where m is the maximum value element in the array comparing the f(mid) with my global ans, and simultaneously also check for mid-1 and mid+1 half{similar that we do ne Binary search with some required modification}
PS:->> I have done 2 hours on this but doesn’t reach to the solution, Please help me if you can.
Its not necessary to check function values of both mid-1 and mid+1.
We know that the function attains the peak in a singular point and from that point the function value increases.So we use the same binary search to calculate the peak value by comparing the function values of mid and mid+1 alone,till the binary search auto finishes by using (l<r) case.
The last value of mid is the answer which we computed in O(n*log n)!
my bad…it can have 2 minima as well, but the conditions i used probably made sure we are choosing the smallest one.[ arr={1,4}, k=1, x=2,3 will give f(x) as 3]
I believe it can be proved mathematically that minima will always lie in a range of at most 2 elements, but i didn’t try to prove it during the contest, and i didn’t think much about it later
@sebastian There will be only two integers x1 and x2such that f(x1) = f(x2)
Differentiating f(x) twice, we find that f''(x) will have only one root corresponding to a single minima/maxima. f'(x) shows that the it will be a minima.
If x is an integer, a single value will give the minima else, two values will give the minima.