forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main6.cpp
43 lines (32 loc) · 1.04 KB
/
main6.cpp
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
/// Source : https://leetcode.com/problems/minimum-cost-for-tickets/
/// Author : liuyubobobo
/// Time : 2019-01-28
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
/// Dynamic Programming
/// No need have 365 states, n states would be enough :-)
/// Since days is in increasing order, we can use binary search to get next state more quickly :-)
///
/// Time Complexity: O(n)
/// Space Complexity: O(len(days))
class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
int n = days.size();
vector<int> dp(n + 1, 0);
dp[n - 1] = costs[0];
for(int i = n - 2; i >= 0; i --){
dp[i] = costs[0] + dp[i + 1];
int i1 = upper_bound(days.begin(), days.end(), days[i] + 6) - days.begin();
dp[i] = min(dp[i], costs[1] + dp[i1]);
int i2 = upper_bound(days.begin(), days.end(), days[i] + 29) - days.begin();
dp[i] = min(dp[i], costs[2] + dp[i2]);
}
return dp[0];
}
};
int main() {
return 0;
}