714.cc 961 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include <vector>
  2. #include <algorithm>
  3. using std::vector;
  4. using std::max;
  5. class Solution {
  6. public:
  7. int maxProfit(vector<int>& prices, int fee) {
  8. // dp[i] means max profit at i with not stock
  9. // dp[i] = max(dp[i - 1], prices[i] + max(dp[j] - prices[j] - fee)), j in [0, i - 1]
  10. // ╰-> tmp
  11. int dp = 0;
  12. if (prices.size() == 0) return dp;
  13. int tmp = -prices[0] - fee;
  14. for (int i = 1; i < prices.size(); i++) {
  15. dp = max(dp, prices[i] + tmp);
  16. tmp = max(tmp, dp - prices[i]- fee);
  17. }
  18. return dp;
  19. }
  20. };
  21. #include <cstdio>
  22. int main() {
  23. Solution *sol = new Solution();
  24. vector<int> prices = {1, 3, 2, 8, 4, 9};
  25. int fee = 2;
  26. int ans = sol->maxProfit(prices, fee);
  27. printf("%d\n", ans);
  28. prices = {1, 1, 1, 1, 1, 1};
  29. fee = 1;
  30. ans = sol->maxProfit(prices, fee);
  31. printf("%d\n", ans);
  32. return 0;
  33. }