Best Time to Buy and Sell Stock

2017-01-06  本文已影响0人  Leonlong

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
ExampleGiven array [3,2,3,1,2], return 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 maxProfit = 0, min = prices[0];
        
        for (int i=1; i < prices.length; i++) {
            int profit = prices[i]-min;
            maxProfit = Math.max(profit, maxProfit);
            min = Math.min(min, prices[i]);
        }
        return maxProfit;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读