leetcode之Best Time to Buy and Sell Stock II
来源:互联网 发布:传奇霸业胸章属性数据 编辑:程序博客网 时间:2024/04/28 04:22
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 <= 1) return 0; int max = 0; int begin = 0,end = 0; for(int i = 1; i < prices.length; i ++){ if(prices[end] > prices[i]){ max += maxProfitByOneTransaction(prices, begin, end); begin = end + 1; end = end + 1; }else{ end ++; } } if(end != begin) max += maxProfitByOneTransaction(prices, begin, end); return max; } public int maxProfitByOneTransaction(int[] prices, int begin, int end) { if(prices == null || prices.length <= 1) return 0; int maxProfit = 0; int maxValue = prices[begin], minValue = prices[begin]; for(int i = begin + 1; i <= end; i ++){ if(maxValue < prices[i]){ maxValue = prices[i]; }else if(minValue > prices[i]){ minValue = prices[i]; maxValue = prices[i]; } if(maxProfit < maxValue - minValue){ maxProfit = maxValue - minValue; } } return maxProfit; } }
0 0
- LeetCode之Best Time to Buy and Sell Stock II
- LeetCode 之 Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- leetcode之Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- LeetCode 之 Best Time to Buy and Sell Stock II
- leetcode之Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- 0基础自学Android(三)
- 撒帝国时代发过士大夫
- 【UvaOJ】【基础题目】【Maths - Number Theory】 10110 - Light, more light
- yongyuan
- 域名解析商搭建创业平台 百万产品免费用
- leetcode之Best Time to Buy and Sell Stock II
- 北方有佳人
- Leetcode 动态规划 Maximum Subarray
- Arcmap没有Spatial Analyst模块
- c#水晶报表的进一步功能和使用!
- ejb的小例子(未能成功运行)
- QT 自动扫描mp3文件
- Android System Property
- Create and Call HttpHandler in SharePoint