Example: I have an array like this: [0,22,56,74,89]
and I want to find the closest number downward to a different number. Let's say that the number is 72
, and in this case, the closest number down in the array is 56
, so we return that. If the number is 100
, then it's bigger than the biggest number in the array, so we return the biggest number. If the number is 22
, then it's an exact match, just return that. The given number can never go under 0, and the array is always sorted.
I did see this question but it returns the closest number to whichever is closer either upward or downward. I must have the closest one downward returned, no matter what.
How do I start? What logic should I use?
Preferably without too much looping, since my code is run every second, and it's CPU intensive enough already.