Middle-题目23:121. 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 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 https://blog.csdn.net/cmershen/article/details/51546333
个人分类: Leetcode
上一篇Middle-题目22:89. Gray Code
下一篇Middle-题目24:46. Permutations
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭