leetcode 買賣股票問題
阿新 • • 發佈:2018-09-06
etc urn leet max leetcode cto stock for public
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 };
leetcode 買賣股票問題