Best Time to Buy and Sell Stock(买卖股票的最佳时机)

问题

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.

Have you met this question in a real interview? Yes
Example
Given array [3,2,3,1,2], return 1.

分析

因为只有一次交易机会,所以找到最小值后,再找到和它的最大差即可。

代码

public class Solution {
    /*
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        int min = Integer.MAX_VALUE;
        int res = 0;
        for (int i : prices) {
            if (i < min) {
                min = i;
            }
            if (i - min > res) {
                res = i - min;
            }
        }
        return res;
    }
}

你可能感兴趣的:(Best Time to Buy and Sell Stock(买卖股票的最佳时机))