当前位置:   article > 正文

Java | Leetcode Java题解之第188题买卖股票的最佳时机IV_leetcode 188 java

leetcode 188 java

题目:

题解:

  1. class Solution {
  2. public int maxProfit(int k, int[] prices) {
  3. if (prices.length == 0) {
  4. return 0;
  5. }
  6. int n = prices.length;
  7. k = Math.min(k, n / 2);
  8. int[] buy = new int[k + 1];
  9. int[] sell = new int[k + 1];
  10. buy[0] = -prices[0];
  11. sell[0] = 0;
  12. for (int i = 1; i <= k; ++i) {
  13. buy[i] = sell[i] = Integer.MIN_VALUE / 2;
  14. }
  15. for (int i = 1; i < n; ++i) {
  16. buy[0] = Math.max(buy[0], sell[0] - prices[i]);
  17. for (int j = 1; j <= k; ++j) {
  18. buy[j] = Math.max(buy[j], sell[j] - prices[i]);
  19. sell[j] = Math.max(sell[j], buy[j - 1] + prices[i]);
  20. }
  21. }
  22. return Arrays.stream(sell).max().getAsInt();
  23. }
  24. }
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号