LeetCode——122. Best Time to Buy and Sell Stock II
来源:互联网 发布:软件研发类期刊 编辑:程序博客网 时间:2024/06/06 19:34
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).
分析:写一个算法进行股票交易,数组代表每天的股票价格,可以多次进行买卖,但是买之前必须先卖出,核心思想,对区间增量进行累加。
代码如下:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2) return 0;
int buy = prices[0];
int result = 0;
for(int i = 1;i<prices.length;i++){
if(buy < prices[i]){
result += prices[i] - buy;//每次增量累加
buy = prices[i];
}else{
buy = prices[i];
}
}
return result;
}
}
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- LeetCode *** 122. Best Time to Buy and Sell Stock II
- leetcode-122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- 【LeetCode】122. Best Time to Buy and Sell Stock II
- LeetCode - 122. Best Time to Buy and Sell Stock II
- java内省机制
- 002_javaScript中事件的冒泡(Bubble)
- Android系统--输入系统(十五)实战_使用GlobalKey一键启动程序
- 二叉搜索树转化为排序双向链表。可以使用中序线索化的方法去进行,在这里需要注意的是我们需要一个记录前一个访问节点的结点。 二叉搜索树转换前: 转换后: 思路:如果根节点的左子树存在,则一直去访
- KRPano
- LeetCode——122. Best Time to Buy and Sell Stock II
- 2n皇后问题
- win7环境下查询端口号占用及杀进程
- SPRING BOOT+WEBMAGIC
- Lua中的元表与元方法学习总结
- Harvesting the Low-hanging Fruits: Defending Against Automated Large-Scale Cyber-Intrusions by Focus
- 百度地图 key 错误,230
- Masonry自动计算cell行高:HYBMasonryAutoCellHeight
- [绍棠_Swift] Swift3.0笔记整理