题目链接: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;
}
}