首页 > 其他分享 >122- Best Time to Buy and Sell Stock II 卖股票II

122- Best Time to Buy and Sell Stock II 卖股票II

时间:2024-05-17 21:09:11浏览次数:27  
标签:Sell Buy int res II prices day stock

题目描述

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the *maximum** profit you can achieve*.

解释:

给定一个数组prices,其中prices[i]表示第i天的股票价格,股票可以当天买,也可以当天卖。但是注意:任何时候最多只能持有一只股票

求获取的最大利润?

基本思想

记录看到的提示:

  • Don't overthink Solution is very simple. The solution simply iterates through the prices array, adding up the profit whenever a price increase is detected from one day to the next.
  • The approach is to iterate through the prices array, identifying upward price movements, and accumulating the profit by adding the differences between consecutive days' prices.

只要判断是一个上升的趋势,利润即可累加。不要将其当成复杂的动态规划问题。

比如[1,2,3] 可以第一天买,第二天卖;第二天卖完,第三天买。或者 第一天买,第三天卖。两种方式本质上利润是一致的。只要是上升的趋势,则可。一旦上升的趋势终止,则要重新开始一个上升趋势,才能累计利润。

对于 [1,4,3,7] 最大利润是什么?是第一天买,第二天卖;第三天买,第四天卖。只要数组显示处于上升趋势,则利润可以增加。

时间复杂度\(O(n)\), 你以为很复杂其实很简单。对于任意一道题目,要有两种思维,简单和复杂。复杂走不通,也许就是简单。

代码

C++

   int maxProfit(vector<int>& prices) {
        int size = prices.size();
        if (size<=1) return 0;
        int res = 0;
        for(int i=1;i<size;++i) {
            if (prices[i]>prices[i-1]) { // 注意当天卖可以当天买回来
                res += prices[i] - prices[i-1];
            } // 其他情况不操作
        }
        return res;
    }

python

    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        if n <= 1: return 0
        res = 0
        for i in range(1, n):
            if prices[i] > prices[i-1]:
                res += prices[i] - prices[i-1]
        return res

标签:Sell,Buy,int,res,II,prices,day,stock
From: https://www.cnblogs.com/douniwanli/p/18198648

相关文章

  • 有效回文 II
    题目链接:来自罗勇军《算法竞赛》尺取法一节的习题。思路:反向扫描,设双指针为\(i\)和\(j\)。if(s[i]==s[j])i++,j--;否则的话要么删除\(s[i]\)或者删除\(s[j]\),看剩下的字符串是否是回文串。classSolution{public:boolcheck(stringstr,intl,intr){......
  • 51模拟IIC-页读写操作
    51代码页读写IIC--模拟IIC#include<reg52.h>#include<intrins.h>sbitSDA=P0^0;sbitSCL=P0^1;sbitLED=P2^0;unsignedcharcodetable[]={0x1c,0X3B,0X2C,0X2D,0X5A,0X5C,0XC5,0X5b};voiddelayms(unsignedintt){unsignedinti,j;fo......
  • 40. 组合总和 II(leetcode)
    https://leetcode.cn/problems/combination-sum-ii/description/classSolution{List<List<Integer>>res=newArrayList<>();LinkedList<Integer>path=newLinkedList<>();intsum=0;publicList<List&l......
  • 抽象代数课程笔记 III —— 域论、伽罗瓦理论
    持续更新。\(\newcommand{\a}{\alpha}\newcommand{\b}{\beta}\newcommand{\D}{\Delta}\newcommand{\eps}{\varepsilon}\newcommand{\ph}{\varphi}\newcommand{\t}{\theta}\newcommand{\la}{\lambda}\newcommand{\si}{\sigma}\newcommand{\d}{......
  • 抽象代数课程笔记 III —— 域论、伽罗瓦理论
    持续更新。\(\newcommand{\a}{\alpha}\newcommand{\b}{\beta}\newcommand{\D}{\Delta}\newcommand{\eps}{\varepsilon}\newcommand{\ph}{\varphi}\newcommand{\t}{\theta}\newcommand{\la}{\lambda}\newcommand{\si}{\sigma}\newcommand{\d}{......
  • 代码随想录算法训练营第第八天 | 344.反转字符串 、541. 反转字符串II、卡码网:54.替
    344.反转字符串建议:本题是字符串基础题目,就是考察reverse函数的实现,同时也明确一下平时刷题什么时候用库函数,什么时候不用库函数题目链接/文章讲解/视频讲解:https://programmercarl.com/0344.反转字符串.html/***@param{character[]}s*@return{void}Donotret......
  • 264 ugly number II 丑数
    问题描述Anuglynumberisapositiveintegerwhoseprimefactorsarelimitedto2,3,and5.Givenanintegern,returnthenth*uglynumber*.解释:一个丑数是一个正整数,其公因子只有2,3,5。给定数字n,求第n个丑数案例:Input:n=10Output:12Explanation:[1,2,......
  • 文章详情URL不使用ID用slug和uuiid代替
    在Laravel中,可以通过使用slug或UUID来展示文章详情和文章列表。这样可以提高URL的可读性和安全性。以下是实现方法和代码示例:方法一:使用Slug数据库字段首先,在posts表中添加slug字段:Schema::table('posts',function(Blueprint$table){$table->string('sl......
  • 本地SSL证书过期 输入命令在IIS自动生成
    C:\Users\win10-zhiyong>dotnetdev-certshttps--trustTrustingtheHTTPSdevelopmentcertificatewasrequested.Aconfirmationpromptwillbedisplayedifthecertificatewasnotpreviouslytrusted.Clickyesontheprompttotrustthecertificate.Suc......
  • 代码随想录算法训练营第第七天 | 454.四数相加II 、383. 赎金信 、15. 三数之和 、18
    454.四数相加II建议:本题是使用map巧妙解决的问题,好好体会一下哈希法如何提高程序执行效率,降低时间复杂度,当然使用哈希法会提高空间复杂度,但一般来说我们都是舍空间换时间,工业开发也是这样。题目链接/文章讲解/视频讲解:https://programmercarl.com/0454.四数相加II.html......