码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-02-07 23:38:53      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:eve   gray   ted   class   head   cal   vertica   san   like   

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. }





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

标签:eve   gray   ted   class   head   cal   vertica   san   like   

原文地址:http://www.cnblogs.com/xiejunzhao/p/b53431464214c560eb29132fb4f2a1fa.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!