LeetCode OJ:Best Time to Buy and Sell Stock II(股票买入卖出最佳实际II)
2015-10-29 22:23
701 查看
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 sz = prices.size(); if(!sz) return 0; int profit = 0; int start = 0; for(int i = 1; i < sz; ++i){ if(prices[i] >= prices[i - 1]) continue; profit += prices[i - 1] - prices[start]; start = i; } profit += prices[sz - 1] - prices[start]; return profit; } };
相关文章推荐
- 杭电1041
- Java基础知识总结
- Mac OS下的wifi配置工具
- Linux netstat命令详解
- 1003我要通过
- PHP实现异步调用方法研究
- 左旋转字符串
- linux 查看目录名称的方法
- LeetCode Contains Duplicate 数组
- 软件缺陷
- Dom4解析xml
- C# DataTable转json
- 清除程序中缓存工具类
- 151029
- SHARED_POOL_RESERVED_SIZE参数的设置及作用 -ZHUANZAI
- mysql 主从同步失败后
- 求100-200之间所有的素数
- 在Windows上安装NumPy、Matplotlib、SciPy和IPython
- 1002写出这个数
- iOS(2)Block的使用