-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1403. Minimum Subsequence in Non-Increasing Order.cpp
More file actions
55 lines (40 loc) · 2.06 KB
/
1403. Minimum Subsequence in Non-Increasing Order.cpp
File metadata and controls
55 lines (40 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//link: 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.
Example 1:
Input: nums = [4,3,10,9,8]
Output: [10,9]
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.
Example 2:
Input: nums = [4,4,7,6,7]
Output: [7,7,6]
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.
Example 3:
Input: nums = [6]
Output: [6]
*/
/*
Runtime: 16 ms, faster than 81.00% of C++ online submissions for Minimum Subsequence in Non-Increasing Order.
Memory Usage: 10.7 MB, less than 100.00% of C++ online submissions for Minimum Subsequence in Non-Increasing Order.
*/
class Solution {
public:
vector<int> minSubsequence(vector<int>& nums) {
int sum = 0;
for(int i = 0; i < nums.size(); i ++){
sum += nums[i];
}
sort(nums.begin(), nums.end());
int i = nums.size() - 1;
int count = 0;
vector<int> ans;
while(sum - count >= count){
count += nums[i];
ans.push_back(nums[i]);
i --;
}
return ans;
}
};