LeetCode 121. Best Time to Buy and Sell Stock 题解 —— Java
2017-03-20 20:11
537 查看
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description
思路:对于数组中的每一个价格,记录当前位置的最低价格,然后计算出若当前售出,能获得的最大利润是多少。比较所有可能的利润,取最大值即为最终的最大利润。
Java代码如下:
public class Solution {
public int maxProfit(int[] prices) {
// 注意特殊情况的判断
if(prices.length == 0){
return 0;
}
int minNum = prices[0];
int[] incomes = new int[prices.length];
incomes[0] = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] < minNum){
minNum = prices[i];
}
incomes[i] = prices[i] - minNum;
}
int maxIncome = 0;
for(int i=0; i<incomes.length; i++){
if(incomes[i]>maxIncome){
maxIncome = incomes[i];
}
}
return maxIncome;
}
}
思路:对于数组中的每一个价格,记录当前位置的最低价格,然后计算出若当前售出,能获得的最大利润是多少。比较所有可能的利润,取最大值即为最终的最大利润。
Java代码如下:
public class Solution {
public int maxProfit(int[] prices) {
// 注意特殊情况的判断
if(prices.length == 0){
return 0;
}
int minNum = prices[0];
int[] incomes = new int[prices.length];
incomes[0] = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] < minNum){
minNum = prices[i];
}
incomes[i] = prices[i] - minNum;
}
int maxIncome = 0;
for(int i=0; i<incomes.length; i++){
if(incomes[i]>maxIncome){
maxIncome = incomes[i];
}
}
return maxIncome;
}
}
相关文章推荐
- leetcode:121. Best Time to Buy and Sell Stock(Java)解答
- leetcode-java-121. Best Time to Buy and Sell Stock
- Java for LeetCode 121 Best Time to Buy and Sell Stock
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- [LeetCode]题解(python):121-Best Time to Buy and Sell Stock
- leetcode(121)(122)(123)(188) Best Time to Buy and Sell Stock I/II/III/IV JAVA代码
- 【小熊刷题】Best Time to Buy and Sell Stock I <leetcode 121 Java>
- LeetCode 121 -Best Time to Buy and Sell Stock ( JAVA )
- LeetCode题解:121. Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock (Java)
- 【leetcode】121. Best Time to Buy and Sell Stock【java】
- LeetCode 121 Best Time to Buy and Sell Stock题解
- LeetCode121:Best Time to Buy and Sell Stock
- leetcode:Best Time to Buy and Sell Stock II 【Java】
- [leetcode]121. Best Time to Buy and Sell Stock[facebook]
- 121. Best Time to Buy and Sell Stock (一) leetcode解题笔记
- [LeetCode]题解(python):122-Best Time to Buy and Sell Stock II
- LeetCode: Best Time to Buy and Sell Stock [121]
- 【Leetcode-Easy-121】Best Time to Buy and Sell Stock