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).

分析:本题的意思就是说你同一时间只能拥有一只股票,在一段时间呢最低时买进,最高时卖出,赚得利润最多。相当于给你一组数组,例如{1,2,3,4,0,2,3,1},在刚开始1时买进,到4时,下一个数字为0了,4是这段时间的最高价,应卖出,然后再买进循环下去,把所得差额加起来就是最大利润了。

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

python实现:

class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
nLen=len(prices)
profit=
if nLen==:
return
elif nLen<=:
return
else:
for i in range(nLen-):
diff=prices[i+]-prices[i]
if diff>:
profit+=diff
return profit

最新文章

  1. EventBus
  2. Oracle数据库体系结构、启动过程、关闭过程
  3. SharePoint 2010 匿名访问开启后不能访问Allitems.aspx或DisplayForm.aspx
  4. Python自动化之语法基础
  5. python 2.7的安装
  6. SLAM学习笔记(1)基本概念
  7. EasyUI--messager
  8. 一条执行4秒的sql语句导致的系统问题 (转)
  9. Java 语言的 XPath API
  10. Chloe.ORM框架应用实践
  11. Java equals() 和hashCode()方法详解
  12. Java工程师成神之路思维导图
  13. Android破解学习之路(十一)—— 关于去更新
  14. javascript数组去重 String字符串去掉两端空格 javascript Array二分法排序 比较 javascript 求和
  15. linux下目录简介——/sys
  16. CentOS 使用yum命令安装出现错误提示”could not retrieve mirrorlist http://mirrorlist.centos.org ***”
  17. Arbiter
  18. MVC控制器使用总结
  19. 跟我学AngularJS:全局变量设置之value vs constant vs rootscope vs 服务[转]
  20. jQuery stop()浅析

热门文章

  1. 【HDOJ】1247 Hat’s Words
  2. HDU 5501 背包问题
  3. Unix/Linux运维首选工具Xmanager Enterprise 3.0的使用教程
  4. 主席树:HDU 4417 Super Mario
  5. 【中途相遇法】【STL】BAPC2014 K Key to Knowledge (Codeforces GYM 100526)
  6. [Locked] Strobogrammatic Number &amp; Strobogrammatic Number II &amp; Strobogrammatic Number III
  7. POJ 1417 True Liars
  8. 005_MyEclipse编码设置
  9. 博客SEO-搜索引擎工作原理简介
  10. WinFrom玩转config配置文件