leetCode Best Time to Buy and Sell Stock II解题分享
来源:互联网 发布:windows xp原装正版iso 编辑:程序博客网 时间:2024/06/06 22:09
原题:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
今天临下班,女朋友催促赶快回家,不多详述了,直接上AC代码,尽可能加上了关键注释,读不懂的可以给我留言我们再讨论
public class BestTimeToBuyAndSellStockII {public int maxProfit(int[] prices) {if(prices == null || prices.length <= 1) {return 0;} int result = 0;int possibleBuyPrice = prices[0];int possibleSellPrice = prices[0];for(int i=1;i<prices.length;i++) {/* * 触发买卖发生的两种情况(经过实验算出来这样是最大收益): * 1)当前的价格,小于possibleSellPrice了,那么用possibleSellPrice-possibleBuyPrice卖出去 * (无论possibleBuyPrice是多少,至少不会比possibleSellPrice高),然后将possibleSellPrice,possibleBuyPrice置为当前价格 * 2)当前的是最后一个(再不卖后面没机会了),并且当前的价格比当前的possibleBuyPrice高,这时候也是要卖的。 */if(prices[i] < possibleSellPrice) {//情况1)result += possibleSellPrice - possibleBuyPrice;possibleBuyPrice = prices[i];possibleSellPrice = prices[i];} else if((i == prices.length -1)&&prices[i] > possibleBuyPrice) {//情况2)result += prices[i] - possibleBuyPrice;}if(prices[i] < possibleBuyPrice) {//当前价格低于possibleBuyPrice,那么修改它 降低可能的进价possibleBuyPrice = prices[i];} else if(prices[i] > possibleSellPrice) {//当前价格高于possibleSellPrice,那么修改它 提高可能的出售价possibleSellPrice = prices[i];}}return result; }}
0 0
- leetCode Best Time to Buy and Sell Stock II解题分享
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- [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
- 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
- Linux常用命令整理
- 数据结构实验之链表七:单链表中重复元素的删除
- android 4.2.2 編譯
- iOS开发笔记之八——设计模式之委托机制
- 2014新生暑假个人排位赛07 A.暑假作业题
- leetCode Best Time to Buy and Sell Stock II解题分享
- POJ 1321 棋盘问题(基础题)
- LeetCode-Convert Sorted Array to Binary Search Tree
- 机房收费系统—《视图》
- memcache的一致性hash算法使用
- 明宣宗书画展
- 黑马程序员之字符串(String)
- new blog
- Acm Club 1326:算法2-8~2-11:链表的基本操作