题目:

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() == ) return ;
int buy_in = prices[], sum = ;
for (int i = ; i < prices.size(); ++i) {
if (prices[i] > buy_in) {
sum += prices[i] - buy_in;
buy_in = prices[i];
} else {
buy_in = prices[i];
}
}
return sum;
}
};

后来在论坛上发现了更加简洁的解法,核心思想其实是比较类似的:

int maxProfit(vector<int> &prices) {
int ret = ;
for (size_t p = ; p < prices.size(); ++p)
ret += max(prices[p] - prices[p - ], );
return ret;
}

其实就是只要有涨就先卖再买,但是这种解法更加简洁清楚。

最新文章

  1. 【转载】 Java线程面试题 Top 50
  2. plist文件的使用
  3. Android开发在路上:少去踩坑,多走捷径
  4. Js_字符串操作
  5. 文件操作II
  6. 使用Google Cloud Platform构建机器学习项目-宠物识别
  7. 计蒜客NOIP模拟赛6 D1T1Diamond-square
  8. 如何在joomla上展示word,pdf,xlsx,ppt
  9. Biorhythms POJ - 1006 中国剩余定理
  10. BZOJ1799 self 同类分布 数位dp
  11. csharp: DefaultValueAttribute Class
  12. 5.27 Test
  13. shell 脚本的时间差计算
  14. Windows消息循环
  15. MySQL:按前缀批量删除表格
  16. Nginx实践03-配置虚拟主机的3种方式
  17. 传智:自己简单实现一个struts2框架的demo
  18. 可以在命令行直接使用密码来进行远程连接和远程拉取文件的命令:sshpass
  19. VS2013新特性
  20. SVN增加文件后,文件无法自动包括在项目中的原因

热门文章

  1. Oracle 12C 新特性之非分区表转分区表online clause(不停业务+索引有效)
  2. Java 程序员快速上手 Kotlin 11 招
  3. 精准准确的统一社会信用代码正则(js)
  4. 手机端的viewport属性
  5. 谈一谈JDK8的函数式编程 (一)
  6. php实现批量修改文件名称
  7. 关于jQuery表单选择中prop和attr的区别。
  8. 你知道“移动端车牌识别”可以嵌入到PDA中应用吗?
  9. 以太坊RLP用法-go-ethereum学习
  10. Asp.Net Core写个共享磁盘文件Web查看器