Leetcode-Best Time to Buy and Sell Stock -java
2017-06-10 15:33
381 查看
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
分析:
思路:贪心算法找出股票最低用来计算最大收益。同一时候保存眼下为止的最大收益,并依据产生的新的最大收益是否是最大来进行更新。
代码:
PS:
Math.max(val1, val2);用来比較val1和val2的大小
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
分析:
思路:贪心算法找出股票最低用来计算最大收益。同一时候保存眼下为止的最大收益,并依据产生的新的最大收益是否是最大来进行更新。
代码:
public class Solution { public int maxProfit(int[] prices) { int lowest = 0; int maxProfit = 0; if(prices.length > 0){ lowest = prices[0]; for(int i = 0; i < prices.length; i++){ if(lowest > prices[i]){ lowest = prices[i]; } maxProfit = Math.max(maxProfit, prices[i] - lowest); } } return maxProfit; } }
PS:
Math.max(val1, val2);用来比較val1和val2的大小
相关文章推荐
- Best Time to Buy and Sell Stock III leetcode java
- LeetCode(122) Best Time to Buy and Sell Stock II (Java)
- Java for LeetCode 122 Best Time to Buy and Sell Stock II
- 【小熊刷题】Best Time to Buy and Sell Stock I <leetcode 121 Java>
- [LeetCode][Java] Best Time to Buy and Sell Stock
- leetcode java Best Time to Buy and Sell Stock
- leetcode JAVA Best Time to Buy and Sell Stock II 3.43 难度系数3
- leetcode:Best Time to Buy and Sell Stock II 【Java】
- [LeetCOde][Java] Best Time to Buy and Sell Stock III
- leetcode:121. Best Time to Buy and Sell Stock(Java)解答
- [Leetcode] Best Time to Buy and Sell Stock II (Java)
- [Leetcode] Best Time to Buy and Sell Stock (Java)
- LeetCode(188) Best Time to Buy and Sell Stock IV (Java)
- leetcode:Best Time to Buy and Sell Stock 【Java】
- Best Time to Buy and Sell Stock leetcode java
- LeetCode(121) Best Time to Buy and Sell Stock (Java)
- LeetCode(123) Best Time to Buy and Sell Stock III (Java)
- 【Leetcode】Best Time to Buy and Sell Stock II in JAVA
- leetcode(121)(122)(123)(188) Best Time to Buy and Sell Stock I/II/III/IV JAVA代码
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】