Leetcode 122 Best Time to Buy and Sell Stock II 贪心

用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。交易次数不限,但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。

关键:能赚就赚

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int ans = 0;
 5         for(int i = 1; i<prices.size(); ++i){
 6             ans += (prices[i] > prices[i-1])? 
 7                     prices[i] - prices[i-1]: 0;
 8         }
 9         return ans;
10     }
11 };

 

posted @ 2016-01-16 20:35  Breeze0806  阅读(126)  评论(0编辑  收藏  举报