Java | Convert to string for easy comparison | Greedy
The merge operation is tricky because, say, we have the following 2 sequences\n\n0, 1, 8 ,5 (A)\n0, 1, 8 ,4 (B)\n\nIf both pointers are at 0, should we pick A o
The merge operation is tricky because, say, we have the following 2 sequences\n```\n0, 1, 8 ,5 (A)\n0, 1, 8 ,4 (B)\n```\nIf both pointers are at 0, should we pick `A` or `B`? \nWe should pick `A` as the resulting sequence would be `0,1,8,5,0,1,8,4`\nWe can either advance both pointers and determine which to pick until they differ or meet the end, \nor we can just convert it to string and use `compareTo()`\n\n```Java\nclass Solution {\n    public int[] maxNumber(int[] nums1, int[] nums2, int k) {\n        String ans="";\n        for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq\n            String one = solve(nums1, i); // find the best seq matching len of i\n            String two = solve(nums2, k-i); // len of k-i\n            StringBuilder sb = new StringBuilder();\n            int a = 0, b = 0;\n            while(a < i || b < k-i){ // merge it to the max\n                sb.append(one.substring(a).compareTo(two.substring(b))>=0?one.charAt(a++):two.charAt(b++));\n            }\n            if (sb.toString().compareTo(ans)>0){ // if better, we replace.\n                ans=sb.toString();\n            }\n        }\n        int[] res = new int[k];\n        for (int i = 0; i < k;++i){\n            res[i]=ans.charAt(i)-\'0\';\n        }\n        return res;\n    }\n\n    private String solve(int[] arr, int k){\n        Deque<Integer> stack = new ArrayDeque<>();\n        for (int i = 0;i<arr.length;++i){\n            while(!stack.isEmpty()&&arr.length-i+stack.size()>k&&stack.peek()<arr[i]){\n                stack.pop();\n            }\n            stack.push(arr[i]);\n        }\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < k;i++){\n            sb.append(stack.pollLast());\n        }\n        return sb.toString();\n    }\n}\n```
['Java']