[LeetCode] Best Time to Buy and Sell Stock(Java)

原创 2016年08月30日 20:02:22

这道题是一道动态规划题

基本可以变形为找每个当前元素之前出现的最小值,然后最小值与当前值做差从而求出最佳时间

我的代码如下

<span style="font-size:24px;">public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0)
            return 0;
        int[] minA = new int[prices.length];
        minA[0] = prices[0];
        int i = 1,max = 0,temp = 0;
        while(i<minA.length){
            if(prices[i]<minA[i-1])
                minA[i] = prices[i];
            else
                minA[i] = minA[i-1];
            temp = prices[i] - minA[i];
            if(temp > max)
                max = temp;
            i++;
        }
        return max;
    }
}</span>

看了网上高票版本与我的一样

2016/8/30

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

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. ...

Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock 本题有一共有四中问题 1. Say you have an array for which the ith element is...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a g...

[LeetCOde][Java] Best Time to Buy and Sell Stock III

题目: Say you have an array for which the ith element is the price of a given stock on day i. ...

Best Time to Buy and Sell Stock

问题一 Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of ...

[LeetCode][Java] Best Time to Buy and Sell Stock IV

题目: Say you have an array for which the ith element is the price of a given stock on day i. ...

LeetCode-121. Best Time to Buy and Sell Stock (Java)

Say you have an array for which the ith element is the price of a given stock on day i. If you we...
  • NOadu
  • NOadu
  • 2017-07-08 15:16
  • 53

Best Time to Buy and Sell Stock

Description:Say you have an array for which the ith element is the price of a given stock on day i. ...

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 we...

LeetCode Best Time to Buy and Sell Stock III && Best Time to Buy and Sell Stock IV

LeetCode这个买股票题,个人认为是出的比较好的,一共四个问题,其中3和4都是hard,在我看来,4的难度比3还是难了不少,因为他涉及到了dp的优化 这里就稍微再提一下第一问和第二问,第一问已经...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)