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.

题目大意:给一个数组,数组的第i个元素是某股票第i天的股价,设计一个算法找出最大的获利。

解题思路:显然买在前,卖在后,这题n^2的做法估计是AC不了的,动规的方式来做吧,F代表获利函数,那么F[i]=price[i]-price[min],其中min<i,如果price[i]<price[min],那么更新min=i。

Talk is cheap>>

    public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) {
            return 0;
        }
        int min_pos = 0;
        int profit = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
            int tmp_pro = prices[i] - prices[min_pos];
            if (prices[i] < prices[min_pos]) {
                min_pos = i;
            }
            profit=Math.max(profit,tmp_pro);
        }
        return profit;
    }
原文地址:https://www.cnblogs.com/aboutblank/p/4405704.html