public class SortedSquare {
    public static int[] sortedSquare(int[] nums) {
        int[] result = new int[nums.length];
        int writeIndex = nums.length - 1;
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            if (nums[l] * nums[l] < nums[r] * nums[r]) {
                result[writeIndex] = nums[r] * nums[r];
                r--;
            } else {
                result[writeIndex] = nums[l] * nums[l];
                l++;
            }
            writeIndex--;
        }
        return result;
    }
    public static void main(String[] args) {
        Utils.printArray(sortedSquare(new int[]{-4, -2, -1, 0, 1, 3, 5}));
    }
}