*(6/1/16)Leetcode 121. Best Time to Buy and Sell Stock

One pass, bug free: 10分钟
1.一切从简单考虑:两种情况,升,降都覆盖到。

public class Solution {
    public int maxProfit(int[] prices) {
        //8:45
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int profit = 0, max_profit = 0;
        int length = prices.length;
        for (int i = 0; i < length; i++){
            if(prices[i] < min){
                min = prices[i];
                max = prices[i];
                profit = max - min;
            }
            else if(prices[i] > max){
                max = prices[i];
                profit = max - min;
            }
            max_profit = Math.max(max_profit, profit);
        }
        return max_profit;
    }
}

解法二:
以上解法并不好,没有体现DP的思想不利于扩展
DP解法: time:O(n); Space:O(n)

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

解法三:
将解法二Space降为O(1):

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        int length = prices.length;
        int left = 0;
        int min = prices[0];
        for(int i = 1; i<length; i++){
            min = Math.min(min, prices[i]);
            left = Math.max(left, prices[i] - min);
        }
        return left;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • tags: 算法, LeetCode, swift, 动态规划 这是最近在学算法中完成的第一个系列题,系列题...
    pointertan阅读 2,345评论 0 0
  • 时常会想起他来。 入行5年,年年月月重复着同样的工作。旁人早已心生倦怠,每日工作时,或应付了事,或满口抱怨、爆粗。...
    乘晚舟阅读 330评论 0 0
  • 你把梦刻在了生活的哪一张?谁为你掀开华丽的帘帐?它又是否把你的相思刻在了心上? 我喜欢水洗过的地方,有冰凉的感觉窜...
    默守静欢阅读 255评论 0 0
  • 文/ 陈皓 或许是为了等待一个人 而你却等来了一朵朵白云 站在边防高山的哨卡上 你无数次阅读那些花草,那些鸟儿 不...
    沂蒙文学阅读 715评论 5 24