Sorted Squares in Descending Order
Problem statement
Given an integer array nums sorted in nondecreasing order, return the square of every element in nonincreasing order, from highest to lowest.
Values may be negative. Preserve duplicate occurrences. Return an empty array when nums is empty.
Try to achieve O(nums.length) time by using the sorted input.
Function
descendingSquares(nums: int[]) → int[]Examples
Example 1
nums = [-4,-1,0,3,10]return = [100,16,9,1,0]The squares [16,1,0,9,100] become [100,16,9,1,0] in highest-to-lowest order.
Example 2
nums = [-3,-1,2]return = [9,4,1]The negative value -3 produces the largest square.
Example 3
nums = [-2,0,2]return = [4,4,0]Both entries with magnitude 2 contribute 4.
Constraints
0 <= nums.length <= 5000.numsis sorted in nondecreasing order.-10000 <= nums[i] <= 10000.