题目:

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 sum_profits = , pre_price = prices[];
for ( size_t i = ; i < prices.size(); ++i )
{
sum_profits += (prices[i]>pre_price) ? prices[i]-pre_price : ;
pre_price = prices[i];
}
return sum_profits;
}
};

tips:

Greedy算法。

核心算法:如果当天的价格比前一天高,sum_profits就累加上当天的利润与前一天利润的差值(即昨天买,今天买);如果当天的价格比昨天低,则不更新sum_profits(即今天买,今天卖)。

========================================

第二次过这道题,低买高卖。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int ret = ;
for ( int i=; i<prices.size(); ++i )
{
if ( prices[i]>prices[i-] )
{
ret += prices[i]-prices[i-];
}
}
return ret;
}
};

最新文章

  1. 一步步开发自己的博客 .NET版(11、Web.config文件的读取和修改)
  2. Java实现多线程并发
  3. 阿里云日志api创建logStore
  4. CUBRID学习笔记 19 sql语句1
  5. 初学java之菜单条,菜单,菜单项的设置
  6. JavaScript高级程序设计(第三版)第三章 基本概念
  7. jeecms获取栏目标题图
  8. 和阿文一起学H5——音乐素材
  9. Memcache存储大数据的问题
  10. python 内置函数 getattr
  11. MyBatis学习总结2
  12. iOS进度指示器——NSProgress
  13. mysql用户修改登录密码及开启远程登录
  14. C语言递归回溯法迷宫求解
  15. TechSmith Camtasia Studio屏幕录像编辑工具
  16. Oracle timestamp类型转换成date类型
  17. RSF 分布式 RPC 服务框架的分层设计
  18. day22 os模块
  19. Java中equals()和hashCode()的关系以及重写equals()和hashCode()的重要性
  20. JSON自定义排序

热门文章

  1. 【转】Nginx跳转任意Http请求到Https
  2. shell实现mysql数据库备份
  3. COGS 201. [BYVoid S1] 埃雷萨拉斯的宝藏
  4. ABAP和Java的destination和JNDI
  5. yield 生成器的运行机制
  6. [转] 防止js全局变量污染方法总结
  7. AngularJs学习笔记-服务
  8. 关于Runtime Issues
  9. 03_14_final关键字
  10. 【线性基 集合hash】uoj#138. 【UER #3】开学前的涂鸦