|
| 1 | +packagecom.fishercoder.solutions; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | +importjava.util.Arrays; |
| 5 | +importjava.util.Collections; |
| 6 | +importjava.util.List; |
| 7 | +importjava.util.stream.Collectors; |
| 8 | + |
| 9 | +/** |
| 10 | + * 1403. Minimum Subsequence in Non-Increasing Order |
| 11 | + * |
| 12 | + * Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. |
| 13 | + * If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, |
| 14 | + * return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. |
| 15 | + * Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * Input: nums = [4,3,10,9,8] |
| 19 | + * Output: [10,9] |
| 20 | + * Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements. |
| 21 | + * |
| 22 | + * Example 2: |
| 23 | + * Input: nums = [4,4,7,6,7] |
| 24 | + * Output: [7,7,6] |
| 25 | + * Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to returned in non-decreasing order. |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * Input: nums = [6] |
| 29 | + * Output: [6] |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * 1 <= nums.length <= 500 |
| 33 | + * 1 <= nums[i] <= 100 |
| 34 | + * */ |
| 35 | +publicclass_1403 { |
| 36 | +publicstaticclassSolution1 { |
| 37 | +publicList<Integer>minSubsequence(int[]nums) { |
| 38 | +List<Integer>list =Arrays.stream(nums) |
| 39 | + .boxed() |
| 40 | + .sorted(Collections.reverseOrder()) |
| 41 | + .collect(Collectors.toCollection(() ->newArrayList<>(nums.length))); |
| 42 | +intsum =list.stream().mapToInt(num ->num).sum(); |
| 43 | +intminSum =0; |
| 44 | +List<Integer>result =newArrayList<>(); |
| 45 | +for (inti =0;i <nums.length;i++) { |
| 46 | +if (minSum > (sum -minSum)) { |
| 47 | +returnresult; |
| 48 | + } |
| 49 | +minSum +=list.get(i); |
| 50 | +result.add(list.get(i)); |
| 51 | + } |
| 52 | +returnresult; |
| 53 | + } |
| 54 | + } |
| 55 | +} |