You are given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: "210"Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 1,000,000,000To form the largest number, we need to decide the order of numbers such that when concatenated, they produce the maximum value. The key insight is that comparing two numbers a and b requires checking which concatenation is larger: a + b or b + a. For example, given 9 and 34, we compare "934" vs "349" and pick the order that gives the larger result.
The brute force approach repeatedly finds the "best" number to place next by comparing all remaining numbers using this concatenation rule, then appends it to the result.
arr[i] + arr[maxi] vs arr[maxi] + arr[i] for all candidates."0").class Solution:
def largestNumber(self, nums: List[int]) -> str:
arr = [str(num) for num in nums]
res = []
while arr:
maxi = 0
for i in range(1, len(arr)):
if arr[i] + arr[maxi] > arr[maxi] + arr[i]:
maxi = i
res.append(arr[maxi])
arr.pop(maxi)
result = "".join(res)
return result if result[0] != '0' else '0'Where is the size of the array and is the total number of digits in the array .
Instead of repeatedly scanning for the best number, we can use sorting with a custom comparator. The comparator determines the order by checking if a + b > b + a. By sorting the entire array once using this rule, numbers naturally arrange themselves so that their concatenation yields the largest possible value.
This approach is more efficient because sorting is faster than repeatedly finding and removing the maximum element.
a and b, place a before b if a + b > b + a."0" (all zeros) by returning "0".Where is the total number of digits in the array .