Here is a high-level process to get the desired results and work for any array data:
- Filter the array keeping on values greater than or equal to the target and then select the lowest remaining value. This is the "best" value (which may be "nothing" if all the values were less) -- this is
O(n)
- Alternatively, sort the data first and see below -- this is
O(n lg n) (hopefully)
Now, assuming that the array is sorted ASCENDING, this approach would work:
- Loop through the array and find the first element which is larger than or equal to the target -- this is
O(n)
And if the array is DESCENDING (as in the post), do as above, but either:
- Iterate backwards -- this is
O(n)
- Sort it ASCENDING first (see fardjad's answer) -- this is
O(n lg n) (hopefully)
- Iterate forwards but keep a look-behind value (to remember "next highest" if the exact was skipped) -- this is
O(n)
Happy coding.