LeetCode 121. Best Time to Buy and Sell Stock 题解 —— Java

来源:互联网 发布:网络麻将群主违法吗 编辑:程序博客网 时间:2024/06/05 09:10

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




0 0