栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

LeetCode:121.买卖股票的最佳时机

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode:121.买卖股票的最佳时机

解题思路:

有利润的情况肯定是从小的开始,向上增加,记录即可,同时特别i情况,后面出现了更小的值,此时有两种情况,1、后面的增率很小,小于前面出现的maxprice,那么maxprice依旧是前面的那个高一点的天投入获得的最大利润2、后面增率很大,差值超过了前面的,那就更不用看了,就是没分情况之前的


代码:

C++:

class Solution {
public:
    int maxProfit(vector& prices) {
        int minprice = INT_MAX, maxprofit = 0;
        for (int price : prices) {
            maxprofit = max(maxprofit, price - minprice);
            minprice = min(minprice, price);
        }
        return maxprofit;
    }
};

python:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        minprice = inf
        maxprofit = 0
        for price in prices:
            maxprofit = max(maxprofit, price-minprice)
            minprice = min(minprice, price)
        return maxprofit

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768776.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号