首页 > 代码库 > 122. 买卖股票 求最大收益2 Best Time to Buy and Sell Stock II

122. 买卖股票 求最大收益2 Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

一天之内可以进行多次买卖操作。
就是求一个数组内,所有递增区间的最大值减最小值之和。
  1. public class Solution {
  2. public int MaxProfit(int[] prices) {
  3. int sum = 0;
  4. for (int tail = prices.Length - 1; tail >= 0;)
  5. {
  6. int head = tail -1;
  7. while (head > 0 && prices[head] < prices[head + 1] && prices[head] > prices[head-1])
  8. {
  9. head--;
  10. }
  11. if (head >= 0)
  12. {
  13. int diff = prices[tail] - prices[head];
  14. if (diff > 0)
  15. {
  16. sum += diff;
  17. }
  18. }
  19. tail = head;
  20. }
  21. return sum;
  22. }
  23. }



null


122. 买卖股票 求最大收益2 Best Time to Buy and Sell Stock II