|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.List; |
| 7 | +import java.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 | +public class _1403 { |
| 36 | + public static class Solution1 { |
| 37 | + public List<Integer> minSubsequence(int[] nums) { |
| 38 | + List<Integer> list = Arrays.stream(nums) |
| 39 | + .boxed() |
| 40 | + .sorted(Collections.reverseOrder()) |
| 41 | + .collect(Collectors.toCollection(() -> new ArrayList<>(nums.length))); |
| 42 | + int sum = list.stream().mapToInt(num -> num).sum(); |
| 43 | + int minSum = 0; |
| 44 | + List<Integer> result = new ArrayList<>(); |
| 45 | + for (int i = 0; i < nums.length; i++) { |
| 46 | + if (minSum > (sum - minSum)) { |
| 47 | + return result; |
| 48 | + } |
| 49 | + minSum += list.get(i); |
| 50 | + result.add(list.get(i)); |
| 51 | + } |
| 52 | + return result; |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments