<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const arr = [-5, -1, 0, 1, 2, 3, 4];
function solution(arr) {
const res = [];
let k = arr.length - 1;
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let leftSqrt = arr[left] * arr[left];
let rightSqrt = arr[right] * arr[right];
if (leftSqrt > rightSqrt) {
res[k--] = leftSqrt;
left++;
} else {
res[k--] = rightSqrt;
right--;
}
}
return res;
}
const res = solution(arr);
console.log(res);
</script>
</body>
</html>