leetcode 买卖股票问题

Posted on 2018-09-06 11:44  走三退二  阅读(376)  评论(0)    收藏  举报

leetcode121 Best Time to Buy and Sell Stock

说白了找到最大的两组数之差即可

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

leetcode122 Best Time to Buy and Sell Stock II

关键在于明白股票可以当天卖出再买进

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