Check for target average pair in sorted array algorithm in JavaScript
Given a sorted array of numbers and a target average value, return whether or not it is possible to achieve the target average value with a pair of numbers from the array.
function canMakeAveragePair(items, target) {
let t = 0;
let h = items.length - 1;
while (t < h) {
const avg = (items[t] + items[h]) / 2;
if (avg === target) {
return true;
} else if (avg < target) {
t++;
} else if (avg > target) {
h--;
}
}
return false;
}
This algorithm is $O(n)$ time and $O(1)$ space.