1. 程式人生 > >【LintCode】 Best Time to Buy and Sell Stock 買賣股票的最佳時機

【LintCode】 Best Time to Buy and Sell Stock 買賣股票的最佳時機

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

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

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0
) return 0; int minPrice = prices[0]; int maxProfit = 0; for(int i = 1; i < prices.length; i++) { maxProfit = Math.max(maxProfit, prices[i] - minPrice); minPrice = Math.min(minPrice, prices[i]); } return maxProfit; } }