Best Time to Buy and Sell Stock II
2016-01-28 12:53
225 查看
题目
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).
方法
和题目一的差别是:能够多次买入和卖出。
这样能够将题目:转换为求解所有上升的线段,仅仅要是上升的都增加到maxPro中去。 相邻的两个数求差,结果大于0。就增加到maxPro中去。
PS:也能够先求解连续的递增。在求差。
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).
方法
和题目一的差别是:能够多次买入和卖出。
这样能够将题目:转换为求解所有上升的线段,仅仅要是上升的都增加到maxPro中去。 相邻的两个数求差,结果大于0。就增加到maxPro中去。
PS:也能够先求解连续的递增。在求差。
public int maxProfit(int[] prices) { if (prices == null) { return 0; } int len = prices.length; if (len == 0 || len == 1) { return 0; } int maxProfit = 0; for (int i = 1; i < len; i++) { int temp = prices[i] - prices[i - 1]; if (temp > 0) { maxProfit += temp; } } return maxProfit; }
相关文章推荐
- find 命令
- 个人对于lower_bound的理解
- 读书笔记 精通CSS 高级Web标准解决方案(第2版)4~8章
- Git 忽略一些文件不加入版本控制
- HDU1495 非常可乐(BFS)
- 在linux系统上如何连接远程服务器
- 腾讯确认放弃开发Win10 Mobile QQ, 太给力了
- Oracle中的job的定时任务
- Leetcode 283. Move Zeroes
- 去年A轮融资的846家创业公司,现在快倒闭完了
- 知道可以做什么样的人,是成长的基础。
- js 导出excle之终极攻略(兼容各大浏览器),纯JS实现
- JFinal Model手动注册到TableMapping中的代码生成器
- android-IPC进程间通信
- 读书笔记 JavaScript 高级程序设计(第三版)-- 第2章
- 【Web前端】:JavaScript常用代码积累
- 使用ceph-deploy进行ceph安装
- ElasticSearch 2 (2) - Setup
- 机房收费系统合作版(三):利用备忘录模式实现取消修改基本数据
- SDK Hello world