java - split a linked list into 2 even lists containing the smallest and largest numbers -
given linked list of integers in random order, split 2 new linked lists such difference in sum of elements of each list maximal , length of lists differs no more 1 (in case original list has odd number of elements). i can't assume numbers in list unique.
the algorithm thought of merge sort on original linked list (o(n·log n) time, o(n) space ) , use recursive function walk end of list determine length, doing splitting while recursive function unwinding. recursive function o(n) time , o(n) space.
is optimal solution? can post code if thinks it's relevant.
no it's not optimal; can find median of list in o(n), put half of them in 1 list (smaller median or equal, upto list size n/2) , half of them in list ((n+1)/2). sum difference maximized, , there no need sort (o(n·log(n)). things done in o(n) (space , time).
Comments
Post a Comment