[코테 풀이] Minimum Subsequence in Non-Increasing Order

시내·2024년 7월 15일
0

Q_1403) Minimum Subsequence in Non-Increasing Order

출처 : https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/

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.

If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, 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.

Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.

class Solution {
    public List<Integer> minSubsequence(int[] nums) {
        List<Integer> res = new ArrayList<>();
        List<Integer> numbers = new ArrayList<>();
        for (int num : nums) numbers.add(num);
        Collections.sort(numbers, Collections.reverseOrder());
        int ind = 0;
        boolean[] visited = new boolean[numbers.size()];
        while (true) {
            int visitedSum = 0, nonVisitedSum = 0;
            res.add(numbers.get(ind));
            visited[ind] = true;
            ind++;
            for (int a = 0; a < visited.length; a++) {
                if (visited[a]) visitedSum += numbers.get(a);
                else nonVisitedSum += numbers.get(a);
            }
            if (visitedSum > nonVisitedSum) break;
        }
        return res;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글