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 121. Best Time to Buy and Sell Stock

噢?一脸黑人问号,这道题目怎么会比之前那题通过率更低?刷完才发现,好像解题方式完全不同,题目的含义大相径庭。题目Say you have an array for which the ith elem...

[121] Best Time to Buy and Sell Stock

给定一个数组,数组里的值为每天产品的价格,你可以进行一次贸易,即一买一卖,如何从这一次贸易中获得最大的利润?

LeetCode121—Best Time to Buy and Sell Stock

LeetCode121—Best Time to Buy and Sell Stock

Leetcode 121 Best Time to Buy and Sell Stock 单次买卖股票最大收益

假设你有一个数组,里面记录的是每一天的股票的价格。 如果你至多只能完成一次交易(即,买一次股票、卖一次股票),设计一个算法来计算最大收益。

leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV

121. Best Time to Buy and Sell Stock [题目] Say you have an array for which the ith element is the p...

【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-121&122&123&188.Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ Say you have an array for which the...

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

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

121. Best Time to Buy and Sell Stock

一、题目概述给定一个数组,其中第i个元素代表第i天股票的价格。 如果你最多被允许完成一次交易(即,购买并抛售一份股票),设计一种算法寻找最大利润。 示例1: Input: [7, 1, 5, 3...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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