zeqing-guo / algorithms-study

MIT License
0 stars 1 forks source link

Leetcode-121: Best Time to Buy and Sell Stock #84

Open zeqing-guo opened 8 years ago

zeqing-guo commented 8 years ago

Description

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.

My Solution

代码的run time是3ms (15.48%),时间复杂度是O(n),空间复杂度是O(1)

public class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if (len <= 1) {
            return 0;
        }
        int minPrice = prices[0];
        int maxProfit = 0;

        for (int i = 1; i < len; ++i) {
            maxProfit = (maxProfit > (prices[i] - minPrice)) ? maxProfit : (prices[i] - minPrice);
            minPrice = (minPrice < prices[i]) ? minPrice : prices[i];
        }

        return maxProfit;
    }
}

Analysis

水题,没什么好说的。