当前位置:网站首页>leetcode122. Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II(简单)
leetcode122. Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II(简单)
2022-07-29 23:27:00 【okokabcd】
一、题目大意
标签: 贪心
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
示例 1:
输入:prices = [7,1,5,3,6,4]
输出:7
解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
总利润为 4 + 3 = 7 。
示例 2:
输入:prices = [1,2,3,4,5]
输出:4
解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
总利润为 4 。
示例 3:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0 。
提示:
- 1 <= prices.length <= 3 * 104
- 0 <= prices[i] <= 104
二、解题思路
每天可以无限次买卖,但是只能持有一支股票。想有最大利润,就得低价买高价卖。如果第二天价格比当前价格高,我们就卖出,把差价加入利润中。若后天价格更高,我们还可以在第二天卖出后再买入。以此类推,遍历完整个数组后即可获得最大利润。
三、解题方法
3.1 Java实现
public class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 1; i < prices.length; i++) {
int tmp = prices[i] - prices[i-1];
res += tmp > 0 ? tmp : 0;
}
return res;
}
}
四、总结小记
- 2022/7/29 原来把题目弄清楚、思路理清楚后,写代码是这么简单
边栏推荐
- [leetcode] 80. Delete duplicates in sorted array II (medium) (double pointer, in-place modification)
- 50. Leetcode 】 【 Pow (x, n) (medium) (power) quickly
- 全国双非院校考研信息汇总整理 Part.3
- SAP ABAP 守护进程的实现方式
- 华为14天-(3)内核开发
- 【openlayers】地图【二】
- DNA修饰碱基5-甲基胞嘧啶和8-羟基鸟嘌呤|DNA修饰量子点|规格信息
- Access the company intranet
- windows下 PHP 安装
- 运动步数抽奖小程序开发
猜你喜欢

Foxmail是什么邮箱?

Access Modbus TCP and Modbus RTU protocol devices using Neuron

线上无序的

How to realize object selection in canvas (5)

Hell Diggers Series #1

Farmers on the assembly line: I grow vegetables in a factory

WLAN笔记

MQTT over QUIC:下一代物联网标准协议为消息传输场景注入新动力

Access the company intranet

使用 Neuron 接入 Modbus TCP 及 Modbus RTU 协议设备
随机推荐
cv.copyMakeBorder(imwrite opencv)
全国双非院校考研信息汇总整理 Part.6
Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)
Design for failure常见的12种设计思想
重庆OI 2005 新年好
资源集合
【openlayers】地图【二】
[2023 School Recruitment Questions] Summary of Common Interview Questions (7. Common Bus Protocols) (Continuously updated with subsequent interviews....)
WLAN笔记
[leetcode] 75. Color classification (medium) (double pointer, in-situ modification)
Dropout回顾
Qt之在QML中使用QSortFilterProxyModel进行排序和过滤
深度学习的随机种子
全国双非院校考研信息汇总整理 Part.3
Access Modbus TCP and Modbus RTU protocol devices using Neuron
微信小程序滑动导航栏(网页浮动窗口怎么设置)
[leetcode] The sword refers to Offer II 006. The sum of two numbers in a sorted array (binary search, double pointer)
Huawei 14 Days - (3) Kernel Development
JVM初探- 内存分配、GC原理与垃圾收集器
[leetcode] 80. Delete duplicates in sorted array II (medium) (double pointer, in-place modification)