[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

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

相关文章推荐

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
  • 103

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

【小熊刷题】Best Time to Buy and Sell Stock I <leetcode 121 Java>

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

【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】

【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Say you have a...

LeetCode(123) Best Time to Buy and Sell Stock III (Java)

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

LeetCode(188) Best Time to Buy and Sell Stock IV (Java)

题目如下: Best Time to Buy and Sell Stock Total Accepted: 43912 Total Submissions: 135635 My Submissions...

【Leetcode】:Best Time to Buy and Sell Stock with Cooldown 问题 in JAVA

这是一道股票买卖的问题,加了一个特殊条件,卖出以后要隔一天才能交易,这道题花了我好久的时间,期间参考了“http://www.cnblogs.com/grandyang/p/4997417.html”...

Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode

直到要用DP做,但是一开始思路是错的。后来参考了 http://blog.csdn.net/pickless/article/details/12034365 才意识到可以在整个区间的每一点切开,然后...

Best Time to Buy and Sell Stock 最佳时间买入卖出股票(一次买入卖出) @LeetCode

package Level2; /** * Best Time to Buy and Sell Stock * * Say you have an array for which the ...

LeetCode:Best Time to Buy and Sell Stock(买卖股票)系列

121. Best Time to Buy and Sell StockSay you have an array for which the ith element is the price of ...
  • BestZem
  • BestZem
  • 2016年07月25日 10:26
  • 249
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[LeetCode] Best Time to Buy and Sell Stock(Java)
举报原因:
原因补充:

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