LintCode 買賣股票的最佳時機(jī)

題目

假設(shè)有一個數(shù)組,它的第i個元素是一支給定的股票在第i天的價格。如果你最多只允許完成一次交易(例如,一次買賣股票),設(shè)計一個算法來找出最大利潤。

樣例
給出一個數(shù)組樣例 [3,2,3,1,2], 返回 1

分析

貪心法,一個記錄目前為止的最小值,一個記錄目前的最大profit,隨時更新即可

代碼

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if(prices == null || prices.length == 0)
            return 0;
        
        int min = Integer.MAX_VALUE;  //store the min value that until now;
        int profit = 0;   //store the profit, initial value is zero;
        
        for(int i:prices) {
            min = Math.min(min, i);
            profit = Math.max(profit, i-min);
        }
        return profit;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容