2015年6月16日星期二

Best Time to Buy and Sell Stock leetcode

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.
维护一个最小值min, 每次递归的profit最大值为max[A[i] - min, profit]
时间复杂O(n) 空间复杂O(1)

public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        if (prices.length <= 1) {
            return profit;
        }
        int low = prices[0];
        for (int i = 0; i < prices.length; i++) {
            low = Math.min(low, prices[i]);
            profit = Math.max(profit, prices[i] - low);
        }
        return profit;
    }
}

没有评论:

发表评论