[leetcode] 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.

https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

思路1:按股票差价组成新数组,diff[i]=prices[i+1]-prices[i],然后求diff数组的最大字段和即可。

思路2:DP。dp[i]表示到第i天可获取的最大利益。dp[i]=max{dp[i-1],prices[i]-curMin}。注意要一直维护一个curMin值。

public class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        int[] dp = new int[len + 1];
        dp[0] = 0;
        int curMin = Integer.MAX_VALUE;

        for (int i = 1; i <= len; i++) {
            dp[i] = Math.max(dp[i - 1], prices[i - 1] - curMin);
            curMin = Math.min(curMin, prices[i - 1]);
        }
        return dp[len];

    }

    public static void main(String[] args) {
        System.out.println(new Solution().maxProfit(new int[] { 2, 8, 4, 9, 3, 6 }));
    }
}

第二遍记录: 注意dp的下标和 prices数组下标相差1,不要搞错了。

第三遍记录:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<=1)
            return 0;
        int n =prices.length;
        int []dp = new int[n+1];
        dp[0]=0;
        int curMin = prices[0];
        for(int i=0;i<n;i++){
            dp[i+1] = Math.max(prices[i]-curMin,dp[i]);
            if(prices[i]<curMin)
                curMin=prices[i];
        }
        
        return dp[n];    
    }
}

参考:

http://www.cnblogs.com/TenosDoIt/p/3436457.html

原文地址:https://www.cnblogs.com/jdflyfly/p/3823401.html