How can I manipulate an array to make the largest number?

前端 未结 16 2129
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  悲哀的现实
    2021-01-30 03:15

    Edit:

    Create an array which contains all possible concats of the initial array

    You get :

    {91 , 19} When combining 1 and 9

    {995 , 959} when 9 and 95

    {917 , 179} when 9 and 17

    from all those tuples get the higher number. and remove from the array the numbers that were used to make that concat string, and from the tuples remove all concats that use those numbers so as to avoid obvious mistake. Find the next big number in the tuples etc... etc...


    I have a general idea as to how I would go about this, but I am not sure how to make it work for any other numbers bigger than 2 digits, maybe this will help you.

    {9,1,95,17,5}

    ok split the array into two arrays with one holding single digit numbers, and one holding the two digits.

    sort them

    you get {95 , 17} and {9,5,1}

    compare if A1[0]+A2[0] > A2[0]+A1[0] lexicographically, eg 959 > 995 ??? (+ in this case is not mathematical addition but string concat)

    and get the bigger of those two

    then you are left with 995 and {17} and {5,1} again, 175 > 517 ?

    you get 995-517 and you are left with {1}

    Hope that helps

提交回复
热议问题