作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Total Accepted: 98941 Total Submissions: 274449 Difficulty: Easy

题目描述

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

题目大意

可以在某一天买股票,在之后卖股票,求最大收益。

解题方法

Java解法

动态规划求解。

因为买股票再卖掉是要求有先后顺序的。肯定是找到当前项的值与之前最小值的差值的最大值。

动态规划问题,可以用数组去写。我偷看别人的,没用数组。

1.保存在见到这个数值时,之前的所有值的最小值。
2.记录当前值与这个最小值的差。
3.找到在所有里边差值的最大值。

不得不说下面这个方法还是很巧的。因为没有笨的像我一样在每个值时都去遍历查找之前所有值的最小值。而是采用保存下来的方法。

public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2) return 0;
int maxProfit=0;
int min=prices[0];
int cur=0;
for(int i=1;i<prices.length;i++){
cur=prices[i];
min=Math.min(min,cur);
maxProfit=Math.max(maxProfit,cur-min);
}
return maxProfit;
}
}

AC:3ms

Python解法

四刷,使用数组分别保存每个数字左边和右边的最小值与最大值,然后我们找到每个位置它右边的最大值-左边的最小值即可。

class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
N = len(prices)
mins = [0] * N
maxs = [0] * N
mins[0] = prices[0]
for i in range(1, N):
mins[i] = min(mins[i - 1], prices[i])
maxs[N - 1] = prices[N - 1]
for j in range(N - 2, -1, -1):
maxs[j] = max(maxs[j + 1], prices[j])
return max(maxs[i] - mins[i] for i in range(N))

二刷,python。只使用了两个变量,保存目前的最小值和当前最大的收益。

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
minPrice = float('inf')
profit = 0
for price in prices:
minPrice = min(minPrice, price)
profit = max(profit, price - minPrice)
return profit

三刷,保存最新的最小值和最大值。这样只用遍历一次,如果遇到更小的值,那么把最小值和最大值同时更新;如果遇到更大的值,那么只更新最大值;最后的结果是最大值和最小值的差。

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
N = len(prices)
res = 0
minP, maxP = float("inf"), 0
for i in range(N):
if minP > prices[i]:
minP = prices[i]
maxP = 0
if maxP < prices[i]:
maxP = prices[i]
res = max(res, maxP - minP)
return res

C++ 解法

五刷,我们在遍历的过程中,始终保持目前最好的收益,那么遍历到最后的结果就是我们要求的。这个思路,在很多题目里面都有运用。

这个题而言,使用变量minP保存当前遇到了的最小值,那么,我们遇到每一个值的时候,都减去当前的最小值就是收益,所有收益最大值就是最大收益。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int minP = INT_MAX;
int res = 0;
for (int p : prices) {
if (p < minP)
minP = p;
res = max(res, p - minP);
}
return res;
}
};

日期

2016/5/1 17:59:24
2018 年 4 月 10 号
2018 年 11 月 11 日 —— 剁手节快乐
2018 年 11 月 17 日 —— 美妙的周末,美丽的天气
2018 年 11 月 24 日 —— 周日开始!一周就过去了~
2019 年 1 月 3 日 —— 2019年已经过去1%

【LeetCode】121. Best Time to Buy and Sell Stock 解题报告(Java & Python & C++)的更多相关文章

  1. 30. leetcode 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 price of ...

  2. leetcode 121. Best Time to Buy and Sell Stock 、122.Best Time to Buy and Sell Stock II 、309. Best Time to Buy and Sell Stock with Cooldown

    121. Best Time to Buy and Sell Stock 题目的要求是只买卖一次,买的价格越低,卖的价格越高,肯定收益就越大 遍历整个数组,维护一个当前位置之前最低的买入价格,然后每次 ...

  3. [LeetCode] 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 ...

  4. LeetCode: 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 gi ...

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

  6. Java for LeetCode 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 ...

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

  8. Python [Leetcode 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 ...

  9. [leetcode]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 ...

随机推荐

  1. 关于单倍型和Phasing

    单倍型,即单倍体基因型,概念很好理解. 单倍型分型的过程就称之Phasing,定相或基因分型. Phasing的意义,在人类疾病遗传和动植物群体遗传中非常重要.也是imputation的必经过程. v ...

  2. vim——批量缩进

    批量缩进 第一种 按esc,退出编辑模式,到命令模式,并在英语输入法下输入":" 将所要批量缩进的行号写上,按照格式:"行号1,行号2>"输入命令,如要将 ...

  3. 分布式事务(4)---最终一致性方案之TCC

    分布式事务(1)-理论基础 分布式事务(2)---强一致性分布式事务解决方案 分布式事务(3)---强一致性分布式事务Atomikos实战 强一致性分布式事务解决方案要求参与事务的各个节点的数据时刻保 ...

  4. javaSE高级篇7 — 设计原则和设计模式 — 设计模式慢慢更( 这是思想层次篇 )

    1.什么是设计原则? 设计原则就是面向对象的原则嘛,即:OOP原则 换句话说:就是为了处理类与类之间的关系( 包括接口.类中的方法 ) 2.OOP设计原则有哪些? 1).开闭原则:就是指对拓展开放.对 ...

  5. [云原生]Docker - 安装&卸载

    目录 系统要求 卸载旧版本 安装Docker 方法一:通过repo安装 设置Repository 安装Docker Engine 升级Docker Engine 方法二:通过package安装 方法三 ...

  6. windows磁盘扩容

    要邻近的磁盘,才可以扩展.所以必须要先删除恢复分区. 删除恢复分区,参考如下: https://jingyan.baidu.com/article/574c5219598d5e6c8c9dc15e.h ...

  7. mybatis-plus分页记坑

    mapper接口方法返回IPage,如果不传page会报npe,底层assert page!=null有啥用?

  8. proguard 混淆工具的用法 (适用于初学者参考)

    一. ProGuard简介 附:proGuard官网 因为Java代码是非常容易反编码的,况且Android开发的应用程序是用Java代码写的,为了很好的保护Java源代码,我们需要对编译好后的cla ...

  9. Hibernate 总结(转)

    JMX:Java Management Extensions.JCA: J2EE Contector ArchitectureJNDI: Java Namind and Directory Inter ...

  10. 删除button中除label之外的View

    因为button中的UIButtonLabel判断class类型时,会被认为是view,所以想删除view类型的子控件时,会将label也删掉,从而无法显示title,此时,可以给指定的View添加t ...