您的位置:首页 > 编程语言 > Java开发

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: