[LeetCode]122. Best Time to Buy and Sell Stock II
来源:互联网 发布:最好的java培训机构 编辑:程序博客网 时间:2024/06/05 17:46
Greedy+Array. Easy mode.我的解法太啰嗦了,标准答案才是真正用到了“greedy”的精髓。
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) { //[7, 1, 5, 3, 6, 4] if(prices.length<2 || prices==null) return 0; int profitSoFar, profitCur, buySoFar, sellSoFar; buySoFar=prices[0]; profitSoFar=profitCur=sellSoFar=0; boolean isSold=false; for(int i=1; i<prices.length; i++){ if(!isSold){ if(buySoFar>=prices[i]) buySoFar=prices[i]; else { profitCur=prices[i]-buySoFar; isSold=true; sellSoFar=prices[i]; } } else{ if(prices[i]<sellSoFar){ isSold=false; buySoFar=prices[i]; profitSoFar+=profitCur; profitCur=0; }else{ sellSoFar=prices[i]; profitCur=prices[i]-buySoFar; } } } profitSoFar+=profitCur; return profitSoFar; }}
Approach #3 (Simple One Pass)
[1, 7, 2, 3, 6, 7, 6, 7]
The graph corresponding to this array is:
From the above graph, we can observe that the sum A+B+C is equal to the difference D corresponding to the difference between the heights of the consecutive peak and valley.
class Solution { public int maxProfit(int[] prices) { int maxprofit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) maxprofit += prices[i] - prices[i - 1]; } return maxprofit; }}
- 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
- C++ 全局变量 静态全局变量 傻傻分不清
- Median of two Sorted Arrays (Frequent++)
- 中奖概率算法(可用于刮刮乐、转盘抽奖)
- 剑指Offer——打印1到最大的n位数(好题)(java实现)
- Linux那些事(2)-Linux编译并运行C语言程序
- [LeetCode]122. Best Time to Buy and Sell Stock II
- luogu P1525 关押罪犯
- HDU 1542 Atlantis(矩形面积并,线段树+离散化+线扫描)
- 1015. 德才论 (vector + sort 排序)
- LDA 与 PLSA对比
- POJ 3252Round Numbers(数位dp)
- 迷宫最小步数
- 微信本地调试神器==Charles入门案例
- iOS自动化测试之一体化平台搭建过程中需要学习的部分知识