|
8 | 8 | Input: [10, 70, 20, 30, 50, 11, 30]
|
9 | 9 |
|
10 | 10 | Output: [[110], [10, 20, 30, 50]]
|
| 11 | + |
| 12 | + |
| 13 | +```java |
| 14 | +public static List<List<Integer>> maxSumIncreasingSubsequence(int[] nums) { |
| 15 | + if(nums == null || nums.length == 0) { |
| 16 | + return new ArrayList<List<Integer>>(); |
| 17 | + } |
| 18 | + int length = nums.length; |
| 19 | + int[] dpTable = nums.clone(); |
| 20 | + int[] sequence = new int[length]; |
| 21 | + Arrays.fill(sequence, Integer.MIN_VALUE); |
| 22 | + int maxSumIndex = 0; |
| 23 | + |
| 24 | + for(int i = 1; i < length; i++) { |
| 25 | + for(int j = 0; j < i; j++) { |
| 26 | + if(nums[j] < nums[i] && dpTable[j] + nums[i] > dpTable[i] ) { |
| 27 | + dpTable[i] = dpTable[j] + nums[i]; |
| 28 | + sequence[i] = j; |
| 29 | + } |
| 30 | + } |
| 31 | + if(dpTable[i] > dpTable[maxSumIndex]) { |
| 32 | + maxSumIndex = i; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + List<List<Integer>> result = buildSequence(nums, sequence, maxSumIndex, dpTable[maxSumIndex]); |
| 37 | + return result; |
| 38 | + } |
| 39 | + |
| 40 | + public static List<List<Integer>> buildSequence(int[] nums, int[] sequence, int maxSumIndex, int maxSum) { |
| 41 | + List<List<Integer>> list = new ArrayList<List<Integer>>(); |
| 42 | + list.add(new ArrayList<Integer>()); |
| 43 | + List<Integer> subsequence = new ArrayList<Integer>(); |
| 44 | + list.add(subsequence); |
| 45 | + list.get(0).add(maxSum); |
| 46 | + while(maxSumIndex != Integer.MIN_VALUE) { |
| 47 | + list.get(1).add(0, nums[maxSumIndex]); |
| 48 | + maxSumIndex = sequence[maxSumIndex]; |
| 49 | + } |
| 50 | + return list; |
| 51 | + } |
| 52 | + |
| 53 | +``` |
0 commit comments