LeetCode 122. Best Time to Buy and Sell Stock II

YOLOv13:目标检测的全面攻略与实战指南 本文是关于 YOLOv13 的全攻略文章。先回顾 YOLO 系列发展,点明 YOLOv13 在该系列中的创新地位,阐述其基于 HyperACE、FullPAD 和轻量级卷积替换等技术的独特优势。深入剖析各核心技术原理,通过与其他版本及实际场景对比展现其性能优势。介绍项目结构与使用方式,分享数据增强、锚框优化等实用技巧,并列举安防监控、自动驾驶等领域应用案例。最后总结 YOLOv13 价值,展望目标检测技术未来发展趋势,为读者提供全面的 YOLOv13 学习与实践指导。 阅读详情

Say you have an array for which the ith element 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 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).


An example will make everything clear!

Suppose we have stock prices as follows:

prices : [1, 2, 3, 1, 2]:

Since I can take as many transactions as I like. A clear buyer will first buy  prices[0], waiting till prices[2], sell the stocks, she can earn 2. Then buy at prices[3] and sell at prices[4]. The main rule here is to buy at lowest price and wait till the top sharp price to sell. But, she need to pay attention to such a condition...

#include <vector>
#include <iostream>
using namespace std;

int maxProfit(vector<int>& prices) {
    if(prices.size() <= 1) return 0;
    int profits = 0;
    int maxProfit = 0;
    int minPrice = prices[0];
    int i = 1, j = 0;
    while(i < prices.size()) {
        if(prices[i] > prices[j]) {
           ;                 // since the stocks are in increasing trend, only idiot will sell...
        } else {
            profits += (prices[j] - minPrice);   // it falls down, sell it!
            maxProfit = max(maxProfit, profits);
            minPrice = prices[i];
        }
      i++;
      j++;
    }
    if(prices[i-1]  > minPrice) maxProfit += prices[i-1] - minPrice;  // pay attention to the last one.
    return maxProfit;
}

int main(void) {
    vector<int> prices{1, 5, 3, 1, 2, 3};
    int profits = maxProfit(prices);
    cout << profits << endl;
}


Output Transcation:

#include "header.h"
using namespace std;

// buy and sell many times.
// requirement: not only output the maxProfit, but also the transactions.
vector< pair<int, int> > maxProfit(vector<int>& prices, int& maxProfit) {
  int profit = 0;
  int i = 1, j = 0, minPriceIndex = 0;
  vector< pair<int, int> > transactions;
  while(i < prices.size()) {
    if(prices[i] >= prices[j]) {;}
    else {
      profit += prices[j] - prices[minPriceIndex];
      if(j - minPriceIndex >= 1)
        transactions.push_back(make_pair(minPriceIndex, j));
      maxProfit = max(maxProfit, profit);
      minPriceIndex = i;
    }
    i++;
    j++;
  }
  if(prices[i-1] > prices[minPriceIndex]) {
    maxProfit += prices[i-1] - prices[minPriceIndex];
    transactions.push_back(make_pair(minPriceIndex, i - 1));
  }
  return transactions;
}

int main(void) {
  vector<int> prices{1, 5, 3, 1, 2, 3};
  int profit = 0;
  vector< pair<int, int> > transactions = maxProfit(prices, profit);
  for(int i = 0; i < transactions.size(); ++i) {
    cout << transactions[i].first << " " <<  transactions[i].second << endl;
  }
  cout << profit << endl;
}

Updated Version, easier to understand

// Buy and Sell as many time as you want.
int maxProfit(vector<int>& prices) {
  if(prices.size() <= 1) return 0;
  int small_price_so_far = prices[0];
  int profit_so_far = 0;
  int i = 1;
  while(i < prices.size()) {
    if(prices[i] > small_price_so_far) {
      int profit = prices[i] - small_price_so_far;
      profit_so_far ++ profit;
      small_price_so_far = prices[i];
    } else { // prices[i] < small_price_so_far, price goes down, buy the stock when reaches the bottom.
      small_price_so_ar = prices[i];
    }
    i++;
  }
  if(prices[i-1] > small_price_so_far) profit_so_far += (prices[i-1] - small_price_so_far);
  return profit_so_far;
}

Facebook asked a interesting one:

/*
  Best time to sell stock II. You can sell the stock as many times as you want.
  Everytime, one sell will cost 3 dollors. How to make the max profit.
*/
#include <vector>
#include <iostream>
using namespace std;
int maxProfit(vector<int>& prices) {
  if(prices.size() <= 1) return 0;
  int i = 1, j = 0;
  int maxProfit = 0;
  int minPrice = prices[0];
  int profits = 0;
  while(i < prices.size()) {
    if(prices[i] > prices[j]) {;}
    else {
      profits += (prices[j] - minPrice) - 3;
      maxProfit = max(maxProfit, profits);
      minPrice = prices[i];
    }
    i++;
    j++;
  }
  if(prices[i - 1] > minPrice) {
    profits += (prices[i-1] - minPrice) - 3;
    maxProfit = max(maxProfit, profits);
  }
  return maxProfit;
}

int main(void) {
  vector<int> prices{1, 5, 3, 1, 2, 3};
  cout << maxProfit(prices) << endl;
}


Another interesting variation!

Say, we can only buy one stock, sell all the bought stocks or not buying not selling each day. Calculate the maximum profit can made.

Example : [0, 2, 10, 3, 4] --> 10 + 8 + 1  = 19, we can buy at 0 and 2, sell it at 10. then buy at 3, sell at 4.

The key point to solve this problem to find the maxValue index and recursively calculating.

 

#include "header.h"
using namespace std;

void maxProfit(vector<int>& array, int left, int right, int& maxValue) {
  if(left >= right) return;
  int max = 0, pos = 0;
  for(int i = left; i <= right; ++i) {
    if(max <= array[i]) {
      max = array[i];
      pos = i;
    }
  }
  for(int i = left; i <= pos; ++i) {
      maxValue += array[pos] - array[i];
  }
  maxProfit(array, pos + 1, right, maxValue);
}


int maxProfit(vector<int>& array) {
  int maxValue = 0;
  int left = 0, right = array.size() - 1;
  maxProfit(array, left, right, maxValue);
  return maxValue;
}

int main(void) {
  vector<int> array {1, 10, 4, 5, 8};
  cout << maxProfit(array) << endl;
}

高速特征金字塔多角度旋转模板匹配(工业零部件缺陷检测C++ Opencv版) 博主在性能较好的笔记本上测试算法全部执行效果大约为45ms,在一般配置的笔记本上博主在性能较好的笔记本上测试算法全部执行效果大约为130ms。下图即为实际检测效果。本文最后附有完整代码:Qt版和MFC版本(可直接运行)。... 阅读详情

相关推荐

codesys【modbusRTU】主站

【代码】modbusRTU【codesys】

cfqq1989的博客 4370

Leetcode_C++笔记之122. Best Time to Buy and Sell Stock II(买卖股票的最佳时机II)

这个题之前做过的,但是忘记了。2、贪心算法求上升区间高度和。

JayShaun的博客 500

机器学习(三) ----------线性回归算法(梯度下降+正则化)

线性回归算法在机器学习中具有核心地位,它以其简单性和直观性为基础,为理解数据间的关系提供了基本框架。作为许多复杂算法的基础,线性回归不仅用于预测目标变量,还用于解释自变量对目标的影响。同时,它也是机器学习入门的经典算法,对于推广机器学习知识和技术具有重要意义。

2301_77539454的博客 1865

【LeetCode】解题122:Best Time to Buy and Sell Stock II

LeetCode解题 122:Best Time to Buy and Sell Stock II Problem 122: Best Time to Buy and Sell Stock II [Easy]解题思路Solution (Java) Problem 122: Best Time to Buy and Sell Stock II [Easy] Say you have an array...

Fayedily的博客 367

Matlab实现PSO-TCN-LSTM-Attention粒子群算法优化时间卷积长短期记忆神经网络融合注意力机制多变量时间序列预测的详细项目实例

这些数据包含了随时间变化她动态信息,具有显著她趋势她、周期她和季节她特征。该模型她核心优势在她其能够自适应地学习数据中她多层次时序信息,捕捉时间序列中她长短期依赖关系,从而提高预测她准确她和可靠她。本项目旨在实她一个基她PTO-TCN-LTTM-TFSttfntion她多变量时间序列预测模型,通过粒子群优化算法优化时间卷积长短期记忆神经网络,并融合注意力机制,提高模型她预测精度和稳定她。本项目模型她实她分为多个阶段,首先她数据预处理,接着她PTO优化,然后她TCN和LTTM网络她构建她训练。

优质创作者: 人工智能技术领域 对于有一定基础的 MATLAB和Python带具体需求都可以详谈 MATLAB和Python可以提供代码调试服务加油 谢谢 你的鼓励是我前行的动力 谢谢支持 加油 谢谢 1078

Matlab实战:用递归最小二乘法(RLS)搞定动态系统参数辨识(附完整代码)

本文通过Matlab实战,详细介绍了如何利用递归最小二乘法(RLS)进行动态系统参数辨识。文章从理论优势切入,提供了完整的仿真数据生成、RLS算法核心实现代码,并对参数收敛过程、预测误差及不同遗忘因子的影响进行了可视化分析与性能评估,为工程实践提供了清晰的指南。

weixin_29035405的博客 502

LeetCode 122. Best Time to Buy and Sell Stock II

题目来源:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 问题描述 122.Best Time to Buy and Sell Stock II Easy Say you have an array for which theithelement is the price of a given stoc...

da_kao_la的博客 186

【RT-DETR有效改进】利用ASF-YOLO改进特征融合层(附代码 + 详细教程)

本文给大家带来的改进机制是ASF-YOLO(发布于2023.12月份的最新机制),其是特别设计用于细胞实例分割。这个模型通过结合空间和尺度特征,提高了在处理细胞图像时的准确性和速度。在实验中,ASF-YOLO在2018年数据科学竞赛数据集上取得了卓越的分割准确性和速度,达到了0.91的box mAP(平均精度),0.887的mask mAP,以及47.3FPS的推理速度,效果非常的好,这个结构本来是用于分割的,我将其移植到了目标检测的模型上,所以其可以适用于分割和目标检测。

Snu77的博客 2292

LeetCode力扣 122. 买卖股票的最佳时机 II Best Time to Buy and Sell Stock II 题解代码 JavaScript

问题https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/ 练习使用JavaScript解答 /** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { if(prices.length < 2) return 0; var arr = []; var .

Coding home - 漂流瓶jz 534

扣子Coze触发器使用指南:实现工作流定时执行的完整教程

Coze平台触发器功能详解:定时触发器配置指南 摘要:Coze平台的触发器是实现自动化任务的核心组件,其中定时触发器能够按预设时间自动执行工作流。本指南介绍了定时触发器的配置方法,包括每日、每周、每月及Cron表达式等多种时间设置方式,以及如何关联工作流执行具体任务。文章还提供了健身提醒等实用案例,并涵盖了触发器调试、发布及常见问题解决方案。通过合理配置定时触发器,用户可以轻松实现各类自动化任务,如定时发送消息、数据采集等,大幅提升工作效率。

互联网架构师笔记 1922

看懂特斯拉IMU底层逻辑,才懂农业机器人不可替代的核心技术壁垒

在自动驾驶与具身智能赛道,特斯拉彻底重构了IMU(惯性测量单元)的技术定位,打破行业“IMU仅为辅助补盲配件”的固有认知,将其从底盘附属硬件升级为纯视觉感知体系的物理核心基座。依托500–1000Hz超高刷新率、无外部依赖的惯性感知能力、端到端神经网络融合架构,特斯拉实现了“视觉感知环境、IMU定义运动”的技术闭环,摆脱对激光雷达、高精地图、卫星定位的强依赖。这套技术逻辑落地农业机器人赛道,不再是技术优化,而是规模化落地的生存刚需。城市自动驾驶属于结构化稳定场景,IMU仅作误差修正的锦上添花;

getusushu的博客 49

【leetcode】41-best-time-to-buy-and-sell-stock-ii 力扣 122. 买卖股票的最佳时机 II

解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4。解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4。随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3。输入:prices = [7,1,5,3,6,4]44.51MB 击败93.87%

738

Android 13 内置xapk安装包的方法

安装xapk 内置xapk

安卓兼职framework和app工程师的博客 222

leetcode 122 Best Time to Buy and Sell Stock II 详细解答

leetcode 122 Best Time to Buy and Sell Stock II 详细解答 解答1 假设有一个图像代表数组: > https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/ 最后需要求得的答案就是,每一段的递增区间的差值。所以得到代码如下: 解法2 上面解法比较hack, 不推荐。 就股票买卖来说,买入股票自身的价格就会 -Price,卖出股票自身的价格就是 +Price. 利

qq_22210659的博客 269

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

LeetCode Array 121 122 Best Time to Buy and Sell Stock I II

Array 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 only permitted to complete at most one transaction (i.e.,...

Yi Jiao's Blog 159

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

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

122. Best Time to Buy and Sell Stock II 一、题目 Problem Description: Say you have an array prices 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 li

KKKKKKOBE_24的博客 297

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

LeetCode 122——Best Time to Buy and Sell Stock II

Say you have an array for which theelement 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 (i.e., buy one a...

CrazyOnes的博客 332

leetcode-122 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 (i.e., buy ...

不思量 238

LeetCode122 Best Time to Buy and Sell Stock II

详细见:leetcode.com/problems/best-time-to-buy-and-sell-stock-ii Java Solution: github package leetcode; /* * Say you have an array for which the ith element is the price of * a given stock

zxwtry的博客 474

【LeetCode-Java实现】122. Best Time to Buy and Sell Stock II

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

IT Crowd的博客 242

Leetcode 122. Best Time to Buy and Sell Stock II

Leetcode 122. 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...

fengran_mark的博客 189

LeetCode 122. Best Time to Buy and Sell Stock II 解题报告

LeetCode 122. Best Time to Buy and Sell Stock II 解题报告

骆小坑的填坑之旅 876

LeetCode 121: Best Time to Buy and Sell Stock && 122 : Best Time to Buy and Sell Stock II

问题描述 思路 两个值记录,一个值记录以i为结束位置为止最大盈利,另一个值记录到现在的最大盈利(可能不是以i为结束位置)。 Java实现 class Solution { public int maxProfit(int[] prices) { int maxCurrent=0; int maxSoFar=0; for(int i ...

zero 219

LeetCode122. Best Time to Buy and Sell Stock II题解

今天讨论一道让我想的过于复杂的题目:一道有关股票买卖的问题。题目描述:Say you have an array for which the i th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many

SYSU_LBY的博客 622

LeetCode122——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...

dingze7757的博客 205

Leetcode: 121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell Stock II

121 Question: 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 o...

兔子窝 238
上一篇: LeetCode 219. Contains Duplicate II
下一篇: LeetCode 169. Majority Element
ActiveCoder
博客等级 码龄11年 4粉丝 345原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值