LEETCODE--Best Time to Buy and Sell Stock II
2017-02-04 22:33
447 查看
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).
参考解释
方法二:略麻烦
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).
参考解释
class Solution { public: int maxProfit(vector<int>& prices) { int len = prices.size(); int profit = 0; for(int i = 1; i < len; i++){ profit += max(prices[i]-prices[i-1], 0); } return profit; } };
方法二:略麻烦
class Solution { public: int maxProfit(vector<int>& prices) { int i = 0; int j = 1; int len = prices.size(); int profit = 0; int pre; while(j < len){ pre = prices[j-1]; if(pre < prices[j]){ j++; if(j == len) profit += prices[j-1] - prices[i]; }else{ cout << pre << endl; profit += pre - prices[i]; i = j; j++; } } return profit; } };
相关文章推荐
- LeetCode_Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- [leetcode刷题系列]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II Solution
- leetcode 61: Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [Leetcode 51] 122 Best Time to Buy and Sell Stock II
- leetcode--Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock I II III
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode: Best Time to Buy and Sell Stock II
- [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)