现在的位置: 首页 > 综合 > 正文

leetcode——Best Time to Buy and Sell Stock

2017年12月22日 ⁄ 综合 ⁄ 共 649字 ⁄ 字号 评论关闭

题目:

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.

思路:

题目中要求,买卖只能有一次,而且必须先买后卖。

因此,该题跟求最大子串和很类似。需要辅助数组p[],标记如果i位置上卖出所能得到的最大收益。

因此,p[0]=0.

若price[i+1]-price[i]>0,则p[i+1] = p[i]+price[i+1]-price[i];

否则,p[i+1]=0;

这就是转换方程。在计算p的同时,记录max。

AC代码:

public int maxProfit(int[] prices) {
        if(prices==null || prices.length==0)
            return 0;
        int [] p = new int[prices.length];
        p[0] = 0;
        int max = 0;
        for(int i=1;i<prices.length;i++){
            if(p[i-1]+prices[i]-prices[i-1]>=0){
                p[i] = p[i-1]+prices[i]-prices[i-1];
            }
            else{
                p[i] = 0;
            }
            max = max>p[i]?max:p[i];
        }
        return max;
    }

抱歉!评论已关闭.