Middle-题目23:121. Best Time to Buy and Sell Stock

原创 2016年05月31日 15:45:50

题目原文:
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.
题目大意:
还是买卖股票,这回限定只能买卖一次,求最大利益。
题目分析:
本题最为简单,最低点买入最高点卖出即可,维护两个变量,一个记录最小值,一个记录当前价格减去最小值的最大值(即以今天价格卖出的profit)。
源码:(language:java)

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0)
            return 0;
        int min = prices[0];
        int profit = 0;
        for(int price:prices) {
            if(price < min)
                min = price;
            if(price - min > profit)
                profit = price - min;
        }
        return profit;
    }
}

成绩:
2ms,beats 60.20%,众数3ms,44.72%
cmershen的碎碎念:
一开始我误以为直接找数组的最大值和最小值相减,但是如果最小值出现在最大值后面就错了。所以维护的不是整个数组的最大值,而且当前值减去min的最大值。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

LeetCode OJ-121. Best Time to Buy and Sell Stock(股票问题)

121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the pri...

121.[Leetcode]Best Time to Buy and Sell Stock

题意 :给你一串股票数字,你有一次的买入和卖出的机会,求最大的收益(卖出-买入)是多少?我的思路:一开始想的是双循环,果断超时。查询了一下这里要用到动态规划的思想:那么什么是动态规划呢? 动态规划...

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

【算法作业6】LeetCode 121. Best Time to Buy and Sell Stock

第六周算法作业:LeetCode 121. Best Time to Buy and Sell Stock

【小熊刷题】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笔记:121. Best Time to Buy and Sell Stock

根据每日股价计算最大收益

leetcode 121. Best Time to Buy and Sell Stock | 最大差值和最大子序列关系

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

LeetCode121/122/123/188 Best Time to Buy and Sell Stock<股票> I/II/III/IIII----DP+Greedy**

一:LeetCode 121 Best Time to Buy and Sell Stock 题目: Say you have an array for which the ith element...

[Leetcode刷题总结系列][Dynamic programming] 121. Best time to buy and sell stock

Leetcode 121. Best time to buy and sell stock

[Leetcode][Dynamic programming] 121. Best time to buy and sell stock

Leetcode 121. Best time to buy and sell stock. Dynamic Programming
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目23:121. Best Time to Buy and Sell Stock
举报原因:
原因补充:

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