[Codewars] Best travel

Best travel

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using namespace std;
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls);
};
int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls) {
vector<vector<int>> dp(k,vector<int>(t + 1));
for(auto l : ls) {
for(int i = t - l; i >= 0; i--) {
for(int j = k-2; j >= 0; j--) {
if(dp[j][i]) dp[j+1][i+l] = 1;
}
}
if(l <= t) dp[0][l] = 1;
}
for(int i = t; i >= 0; i--) if(dp[k-1][i]) return i;
return -1;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/29/PS/Codewars/best-travel/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.