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

题目大意:

类似I,只不过现在允许进行多次交易,只需在上升曲线累加收益即可,即所谓的贪婪算法。

(贪婪算法与动态规划的区别:贪婪算法只需在每一步求出最大收益,即可在最后一步得到总的最大利润,而对于动态规划,每一步的最大收益可能受到前面某一步的影响,导致必须在最后一步综合前面的状态才能得出最大利润)

Java解法:

public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int profit = 0;
int temp = prices[0];
for(int i = 1; i<prices.length; i++){
if(prices[i] > temp) //上升曲线每步累加收益
profit += prices[i] - temp;
temp = prices[i];
}
return profit;
}
}

最新文章

  1. git查看本地和创建分支、上传分支、提交代码到分支、删除分支等,git分支、git查看本地和创建分支以及上传分支到服务器
  2. SqlLite 基本操作
  3. Android FragmentTransactionExtended:使Fragment以多种样式动画切换
  4. Java-继承,多态0922-05
  5. eclipse常用快捷键及调试方法(虽然现在看不懂,但是感觉以后肯定会用到,先转了)
  6. SQL Server 2008 R2——开发资料搜集
  7. js 原型的内存分析
  8. Azure SQL 数据库:服务级别与性能问答
  9. js事件模型
  10. bzoj 3043 (差分序列运用)
  11. Java中的HashMap和Hashtable
  12. JSP标准标签库(JSTL)--XML标签库 x
  13. hackerrank DFS Edges
  14. linux只端口监听及杀死进程
  15. Mybatis框架基础支持层——反射工具箱之泛型解析工具TypeParameterResolver(4)
  16. centos7.2 环境下 mysql-5.1.73 安装配置
  17. 模拟select控件,css模拟下拉
  18. java算法面试题
  19. c++ 容器填充指定长度(fill_n)
  20. OC基础:实例变量和成员变量的区别 分类: ios学习 OC 2015-06-14 17:59 16人阅读 评论(0) 收藏

热门文章

  1. phpstorm xdebug调试设置样式
  2. [深入React] 3.JSX的神秘面纱
  3. 怎样修复“Windows/System32/Config/System中文件丢失或损坏”故障
  4. laravel敏捷应用
  5. 关于 视频同步vsync 信号在不同一时候钟域採样问题
  6. Python:常见错误集锦(持续更新ing)
  7. 基于Spring MVC的简单HelloWorld实例
  8. HTML写的第一个邮箱登陆界面
  9. const的重载
  10. POJ3111 K Best(另类背包+二分+变态精度)