[LeetCode]Best Time to Buy and Sell Stock II
2016-04-06 21:39
344 查看
题目描述:
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).
解题思路:
贪心算法:只要当前值比前一个值小,就更新利润。
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).
解题思路:
贪心算法:只要当前值比前一个值小,就更新利润。
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() == 0 || prices.size() == 1) { return 0; } int min_index = 0; int profit = 0; for (int i = 1; i < prices.size(); ++i) { if (prices[i] < prices[i - 1]) { profit += prices[i - 1] - prices[min_index] > 0? prices[i - 1] - prices[min_index] : 0; min_index = i; } } if (prices[min_index] < prices[prices.size() - 1]) { profit += prices[prices.size() - 1] - prices[min_index]; } return profit; } };
相关文章推荐
- 通过STL中的string看写时拷贝和读时拷贝
- php热门资料
- slf4j 和 log4j合用的(Maven)配置
- Am 开发 intern
- HDOJ 1709-The Balance【模拟】
- Windows Server 2008 R2 AD导入大批量的用户账户
- UIAlertController(UIActionSheet、UIAlertView)
- 复利计算-结对
- DOM元素querySelectorAll和querySelector
- 算法_动态规划_最长单调递增子序列
- 百度地图循环添加个标点及信息框
- 微软笔试 Font Size
- HDU 1069 Monkey and Banana
- 求因子(1405)
- 建立名称server
- 复利计算-结对
- 1050 Moving Tables(贪心-4)
- CSS3秘笈复习:第十一章
- 机房重构之泛型集合的应用
- FZU FOJ 2030 括号问题【dp】||【暴搜+栈判断括号匹配】