Skip to content

Commit 0892fa7

Browse files
authored
Merge pull request #74 from samkit96/master
Add cpp code for leetcode problem
2 parents df08811 + b20f798 commit 0892fa7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Problem link: https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/
3+
* Solution:
4+
* (1) Find the sum of all the elements of the vector.
5+
* (2) Sort the vector in descending order.
6+
* (3) Keep on subtracting the elements from the highest to lowest (greedily) until the sum of highest elements is greater than the remaining. Also,add the elements to the answer vector.
7+
* (4) The required elements till the condition meets is the final answer.
8+
* (5) Return them in non decreasing order.
9+
*/
10+
11+
class Solution {
12+
public:
13+
vector<int> minSubsequence(vector<int>& nums) {
14+
15+
int n = nums.size();
16+
17+
sort(nums.begin(), nums.end());
18+
19+
int tot = 0;
20+
for(int i=0 ; i<n ; i++) tot += nums[i];
21+
22+
vector<int> ans;
23+
int sum = 0;
24+
25+
for(int i=n-1 ; i>=0 ; i--) {
26+
sum += nums[i];
27+
int sumNonAns = tot-sum;
28+
29+
if (sum > sumNonAns) {
30+
for (int j=n-1 ; j>=i ; j--) ans.push_back(nums[j]);
31+
return ans;
32+
}
33+
}
34+
35+
return nums;
36+
}
37+
};

0 commit comments

Comments
 (0)