lintcode-medium-Best Time to Buy and Sell Stock II
2016-03-14 16:37
357 查看
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).
Given an example [2,1,2,0,1], return 2.
这题就简单一点,因为可以随意做任意交易,所以只要后一天比前一天价格高,就可以在profit中加上这个差值
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).
Given an example [2,1,2,0,1], return 2.
这题就简单一点,因为可以随意做任意交易,所以只要后一天比前一天价格高,就可以在profit中加上这个差值
class Solution { /** * @param prices: Given an integer array * @return: Maximum profit */ public int maxProfit(int[] prices) { // write your code here if(prices == null || prices.length == 0) return 0; int profit = 0; for(int i = 1; i < prices.length; i++){ if(prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; } return profit; } };
相关文章推荐
- InitGoogleLogging坑爹
- C# zip压缩
- 数据仓库专题20-案例篇:电商领域数据主题域模型设计v0.1(改进意见征集中)
- HAproxy指南之haproxy配置详解1(理论篇)
- 内核启动错误:use vmalloc=<size> to increase size.
- 309.Best Time to Buy and Sell Stock with Cooldown
- Android设计模式系列(2)--SDK源码之观察者模式
- 浅谈MVP
- [BZOJ 3211] 花神游历各国
- 设计模式总结
- 死锁、活锁、优先级翻转
- RecyclerView下拉刷新和加载更多
- iOS单元测试
- libcurl的使用
- CodeForces 622C Not Equal on a Segment
- 百度糯米产品分析
- Android 如何进行js交互
- ios 中NULL,nil, Nil, NSNull的区别
- SSL和HTTPS的设置
- Hibernat org.hibernate.MappingException: Could not determine type for: java.util.Set