Leetcode - Greedy Algorithm - Best Time to Buy and Sell Stock

该数据集收录了国内主要期货商品和股指指数的日频行情 商品期货覆盖有色、黑色、能化、农产品等板块,包含铜、螺纹钢、原油、豆粕等活跃合约 股指指数部分涵盖沪深300、上证50、中证500等品种 每个品种提 该数据集收录了国内主要期货商品和股指指数的日频行情。商品期货覆盖有色、黑色、能化、农产品等板块,包含铜、螺纹钢、原油、豆粕等活跃合约。股指指数部分涵盖沪深300、上证50、中证500等品种。每个品种提供统一字段:合约代码、交易日期、开盘价、最高价、最低价、收盘价、结算价、成交量和持仓量。数据按交易日顺次排列,未做复权处理,直接反映交易所原始发布信息。 数据源:CMES金融数据库 立即下载

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.

解法1:最大值-最小值。

解法2:最大子序列和

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.empty())
            return 0;
        vector<int>::iterator beg=prices.begin();
        int maxPro=0,curMinPrice=*beg;
        for(;beg!=prices.end();beg++)
        {
            maxPro=max(maxPro, *beg-curMinPrice);
            curMinPrice=min(curMinPrice, *beg);
        }
        return maxPro;
    }
};

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.empty())
            return 0;
        int maxPro=0,tempPro=0;
        vector<int>::iterator beg=prices.begin();
        int curPrice=*beg;
        for(;beg!=prices.end();beg++)
        {
            tempPro+=*beg-curPrice;
            curPrice=*beg;
            if(tempPro<0)
                tempPro=0;
            if(tempPro>maxPro)
                maxPro=tempPro;
        }
        return maxPro;
    }
};



Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解析:求相邻数组元素增长的和。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.empty())
            return 0;
        vector<int>::iterator beg=prices.begin();
        int maxPro=0, curPrice=*beg;
        for(; beg!=prices.end();beg++)
        {
            if(*beg>curPrice)
                maxPro+=*beg-curPrice;
            curPrice=*beg;
        }
        return maxPro;
    }
};



Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解析:见注释,该算法将空间复杂度降低为O(1)

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // 空间负杂度为O(1),时间复杂度为O(n)
        if(prices.size()<=1)
            return 0;
        int minPriceIndex=0,maxPriceIndex=0;
        int maxPro=0,maxTemp=0,curPriceIndex=0,curMinPriceIndex=0;
        // 首先找出只做一次交易最大的收益maxPro,并记录买入时下标minPriceIndex和卖出时下标maxPriceIndex
        for(int i=1;i<prices.size();i++)
        {
            maxTemp+=prices[i]-prices[curPriceIndex];
            curPriceIndex=i;
            if(maxTemp<0)
            {
                maxTemp=0;
                curMinPriceIndex=curPriceIndex;
            }
            if(maxTemp>maxPro)
            {
                maxPro=maxTemp;
                minPriceIndex=curMinPriceIndex;
                maxPriceIndex=i;
            }
        }
        // 在买入下标minPriceIndex之前最大的收益maxProAhead
        int maxProAhead=0,curMinPriceAhead=prices[0];
        for(int i=1;i<minPriceIndex;i++)
        {
            maxProAhead=max(maxProAhead,prices[i]-curMinPriceAhead);
            curMinPriceAhead=min(prices[i], curMinPriceAhead);
        }
        // 再卖出下标maxPriceIndex之后最大的收益maxProBehind
        int maxProBehind=0;
        if(maxPriceIndex+1<prices.size())
        {
            int curMinPriceBehind=prices[maxPriceIndex+1];
            for(int i=maxPriceIndex+1;i<prices.size();i++)
            {
                maxProBehind=max(maxProBehind,prices[i]-curMinPriceBehind);
                curMinPriceBehind=min(prices[i], curMinPriceBehind);
            }
        }
        // 再买入之后到卖出之前,最大的跌幅minProMid
        int minProMid=0,curMaxPrice=prices[minPriceIndex];
        for(int i=minPriceIndex+1;i<maxPriceIndex;i++)
        {
            minProMid=min(minProMid, prices[i]-curMaxPrice);
            curMaxPrice=max(prices[i],curMaxPrice);
        }
        // max1表示maxPriceIndex之前两次最大的收益和
        // max2表示minPriceIndex之后和maxPriceIndex之间,除去最大跌幅的收益
        // max3表示minPriceIndex之后两次最大的收益和
        int max1=maxProAhead+maxPro,max2=maxPro-minProMid,max3=maxPro+maxProBehind;
        return max1>(max2>max3?max2:max3)?max1:(max2>max3?max2:max3);
                
    }
};



腾讯音乐 QQ音乐商业化客户端开发工程师:岗位深度解析与面试攻略 腾讯音乐QQ音乐商业化客户端开发工程师岗位要求3年以上Android开发经验,熟练掌握Kotlin/Java及跨端开发技术。核心职责包括QQ音乐客户端功能开发、架构优化、性能提升及技术攻关。岗位要求计算机相关本科以上学历,具备完整项目开发经验,熟悉TCP/IP等网络协议,能独立解决复杂技术问题。面试重点考察项目经验、架构设计、性能优化及新技术研究能力,建议候选人准备具体案例,量化成果,并熟悉Flutter等跨端技术。该职位强调技术深度与产品思维的结合,需展现扎实的编程基础、问题解决能力和团队协作精神。 阅读详情

相关推荐

RDD2022 数据格式转换与清洗

Rdd2022数据集,是关于道路损伤的数据集,与rdd2020相比增加了两万多张图片但是由于格式不能被yolo直接使用且其中有大量的图片没有符合要求的标注,特写此文章记录数据清洗与格式化的过程。

蓝胖子的博客 9957

Leetcode_Best Time to Buy and Sell Stock II

Tag Array\Greedy Difficulty Easy Description Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may comple

大锅八十小锅四十 339

脑机接口(BCI)从原理到开发实战 10|脑控外设:用脑电波控制机械臂/游戏

摘要: 脑机接口(BCI)的“最后一公里”是将分类结果转化为实际动作的关键环节。本文介绍如何通过指令映射、硬件通信和执行反馈实现脑控外设,包括离散/连续控制策略、防抖处理及串口/蓝牙通信方法。通过两个实战案例(运动想象控制机械臂抓取、P300/SSVEP控制游戏)和完整项目(OpenBCI控制小车),演示了从分类标签到设备动作的完整流程,重点涵盖指令生成算法(多数投票)、Python与Arduino的串口通信集成,为BCI系统落地提供实用解决方案。(149字)

小明的博客 766

[leetcode]122. Best Time to Buy and Sell Stock II

greedy题目: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 s

qq_24896641的博客 233

CM-GAI:基于连续介质力学与最优传输的数据生成新范式

在数据驱动的工程与科学研究中,如何利用有限的物理数据实现可靠预测是核心挑战。传统方法如深度神经网络,在数据稀缺时往往泛化能力不足且缺乏物理一致性。为解决此问题,一种融合物理原理与数据驱动的新范式应运而生。其核心思想是将数据分布的变化类比为连续介质在广义力驱动下的力学变形过程,通过最优传输理论为分布变换提供最优路径的度量。这种方法将物理规律(如质量守恒、运动方程)作为硬约束嵌入模型,确保了生成过程的物理可解释性。物理信息神经网络(PINNs)则被用作高效求解器,处理高维特征空间中的复杂控制方程。在工程实践中,

weixin_30607029的博客 608

动态表单设计

自定一表单数据结构。内容展示如有必要行转列。前端根据题目类型自定义组件后端跟俊题目类型用策略模式校验各种类型这样有统计功能的简单动态问卷就可以了展示时可能某些场景需要行转列。大概估摸使用的话有可能kmic_form_data_detail表的记录数比较大,后期再考虑数据或者表迁移或拆分。

zquwei的博客 3465

LeetCode 122. Best Time to Buy and Sell Stock II (买卖股票的最好时机之二)

Say you have an array for which theithelement is the price of a given stock on dayi. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one ...

weixin_30273931的博客 117

波动性GARCH模型与波动率预测(代码+结果分析)

本文介绍的ARCH、GARCH模型可以刻画出随时间变化的条件异方差。

celiaweiwei的博客 2万+

Jasna 免费视频马赛克修复指南:RTX 5090 上 34 秒修完 1080p

你有一段 1080p 视频,画面里盖着马赛克,想把它修干净。用 Jasna,RTX 5090 上整段 3 分 22 秒的 1080p 视频,免费 BasicVSR++ 模型修完只要 **34 秒**。它是个 GPU 视频马赛克修复工具:检测、跟踪、修复、拼接、编码全自动,图形界面和命令行都能用。官方发行包按系统和 GPU 厂商下载解压即可,不用自己装依赖。 ## 先判断:你的设备适不适合跑 |

gitblog_00453的博客 438

决策树简介/PPT

最近给我们组新生讲了决策树的相关知识,以下是所做的PPT,参考了网络资源。

垃圾就应该待在垃圾桶里的博客 3796

DeepSeek 赋能招投标全流程智能化:多模态解析、知识图谱与投标文件自动生成实战指南(附完整代码与行业案例)

摘要:本文深入探讨DeepSeek技术在招投标领域的全流程智能化应用,通过整合自然语言处理(NLP)、多模态解析、知识图谱等核心技术,实现招标文件智能解析与投标文件自动生成。文中详细解析DeepSeek-R1模型的多模态处理机制、动态知识图谱构建方法及智能模板填充算法,通过完整代码实现展示技术细节。结合广某资源交易平台、山西XX"XX云"等典型案例,验证技术方案在提升招投标效率、降低人为错误方面的显著效果。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1464

LeetCode - Fibonacci Sequence/Dynamic Programming - Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

小熊糖否——木子兮的自留地 1043

C++面试八股文

和静态多态(又称编译期多态,即在系统编译期间就可以确定程序将要执行哪个函数),其中动态多态是通过虚函数实现的,虚函数是类的成员函数,存在存储虚函数指针的表叫做虚函数表,虚函数表是一个存储类成员虚函数的指针,每个指针都指向调用它的地方,当子类调用虚函数时,就会去虚表里面找自己对应的函数指针,从而实现“谁调用、实现谁”从而实现多态。而C++符号表中的符号不是以函数名命名的,称为函数名修饰规则,虽然函数名相同,但是函数参数等其他属性不同,取的符号也不同,所以不会产生查询歧义的问题,使得函数可以重载。

qq_46676829的博客 905

Leetcode - Bit Operation/Array- Single Number

Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using ext

小熊糖否——木子兮的自留地 983

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Leetcode - Median of Two Sorted Array

利用分治算法的Merge算法,算法的复杂度应该是merge算法的一半,虽然leetcode显示Accepted,但是时间复杂度应该没有满足。时间复杂度为:O((n+m)/2)

小熊糖否——木子兮的自留地 549

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Leetcode - Tree - Symmetric Tree

1、Same Tree /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */

小熊糖否——木子兮的自留地 527

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Leetcode - Pointers/Array - Remove Element

Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length.

小熊糖否——木子兮的自留地 513

Leetcode - Tree - Balanced Binary Tree

Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never diffe

小熊糖否——木子兮的自留地 514

Leetcode - Tree - Same Tree

Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

小熊糖否——木子兮的自留地 509

Leetcode - Tree /Dynamic Programming- Unique Binary Search

Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \

小熊糖否——木子兮的自留地 507

Leetcode - Tree - Binary Tree Traversal

1、Binary Tree Preorder Traversal

小熊糖否——木子兮的自留地 487

Leetcode - vector\stack - Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1",

小熊糖否——木子兮的自留地 486

Leetcode - Tree - Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. /** * Definition for binary tree *

小熊糖否——木子兮的自留地 483

Leetcode - string - Reverse Words in a String

class Solution { public: void reverseWords(string &s) { istringstream record(s); string temp; vector vec; while(record>>temp) { vec.push_back(te

小熊糖否——木子兮的自留地 462

Leetcode - Pointers/Array - Two sum

排序的方法 class Solution { public: vector twoSum(vector &numbers, int target) { vector temp=numbers; int numBegin=0; int numEnd=numbers.size()-1; vector iRet;

小熊糖否——木子兮的自留地 458

Leetcode - Pointers - Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with

小熊糖否——木子兮的自留地 457
上一篇: Leetcode - Bit Operation/Array- Single Number
下一篇: Leetcode- List - Linked List Cycle
JerkWisdom
博客等级 码龄14年 70粉丝 76原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值