Skip to content

Commit fb11253

Browse files
committed
#237 & #240 & #264 solutions
1 parent 2b03b71 commit fb11253

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

house-robber/ys-han00.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int rob(vector<int>& nums) {
4+
vector<int> dp(nums.size(), 0);
5+
6+
dp[0] = nums[0];
7+
if(dp.size() == 1)
8+
return dp[0];
9+
10+
dp[1] = nums[1];
11+
int ans = max(dp[0], dp[1]);
12+
13+
for(int i = 2; i < dp.size(); i++) {
14+
int maxi = -1;
15+
for(int j = 0; j < i - 1; j++)
16+
maxi = max(dp[j], maxi);
17+
dp[i] = maxi + nums[i];
18+
ans = max(ans, dp[i]);
19+
}
20+
21+
return ans;
22+
}
23+
};
24+
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <bits/stdc++.h>
2+
3+
class Solution {
4+
public:
5+
int longestConsecutive(vector<int>& nums) {
6+
if(nums.size() == 0)
7+
return 0;
8+
9+
sort(nums.begin(), nums.end());
10+
11+
int ans = 1, cnt = 1;
12+
for(int i = 1; i < nums.size(); i++) {
13+
if(nums[i] == nums[i - 1])
14+
continue;
15+
if(nums[i] - 1 == nums[i - 1])
16+
cnt++;
17+
else
18+
cnt = 1;
19+
ans = max(cnt, ans);
20+
}
21+
22+
return ans;
23+
}
24+
};
25+
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <bits/stdc++.h>
2+
3+
class Solution {
4+
public:
5+
vector<int> topKFrequent(vector<int>& nums, int k) {
6+
map<int, int> count;
7+
8+
for(int i = 0; i < nums.size(); i++) {
9+
if(count.find(nums[i]) == count.end())
10+
count[nums[i]] = 1;
11+
else
12+
count[nums[i]]++;
13+
}
14+
15+
vector<pair<int, int>> cnt(count.begin(), count.end());
16+
sort(cnt.begin(), cnt.end(), cmp);
17+
18+
vector<int> ans;
19+
for(int i = 0; i < k; i++)
20+
ans.push_back(cnt[i].first);
21+
22+
return ans;
23+
}
24+
25+
static bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
26+
return a.second > b.second;
27+
}
28+
};
29+

0 commit comments

Comments
 (0)