# @param {Integer[]} nums
# @return {Integer[]}
def sorted_squares(nums)
    result = []

    split = nums.find_index { |x| x >= 0 }

    i, j = nil, nil
    if split == nil then
        i, j = nums.size - 1, nums.size
    else
        i, j = split - 1, split
    end

    while i >= 0 and j < nums.size do
        i_s = nums[i] * nums[i]
        j_s = nums[j] * nums[j]

        if i_s < j_s then
            result.push(i_s)
            i -= 1
        else
            result.push(j_s)
            j += 1
        end
    end

    while i >= 0 do
        result.push(nums[i] * nums[i])
        i -= 1
    end

    while j < nums.size do
        result.push(nums[j] * nums[j])
        j += 1
    end

    return result
end

RSpec.describe "rotate" do
    it "nums = [-4,-1,0,3,10]" do
        expect(sorted_squares([-4,-1,0,3,10])).to eq([0,1,9,16,100])
    end

    it "nums = [-7,-3,2,3,11]" do
        expect(sorted_squares([-7,-3,2,3,11])).to eq([4,9,9,49,121])
    end

    it "nums = [-7,-3,0,0,0,0,2,3,11]" do
        expect(sorted_squares([-7,-3,0,0,0,0,2,3,11])).to eq([0,0,0,0,4,9,9,49,121])
    end

    it "nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]" do
        expect(sorted_squares([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])).to eq([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
    end
end