当前位置:网站首页>LeetCode122. 买卖股票的最佳时机II
LeetCode122. 买卖股票的最佳时机II
2022-06-28 20:59:00 【Yuyy】
本文最后更新于 484 天前,其中的信息可能已经有所发展或是发生改变。
一、思路
找出选择和状态
二、问题
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。示例 2:
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。示例 3:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。提示:
1 <= prices.length <= 3 * 10 ^ 40 <= prices[i] <= 10 ^ 4
Related Topics
- 贪心算法
- 数组
\n
- 1107
- 0
三、代码
public int maxProfit(int[] prices) {
if (prices.length < 2) {
return 0;
}
int[][] arr = new int[prices.length][2];
arr[0][1] = -prices[0];
arr[0][0] = 0;
for (int i = 1; i < prices.length; i++) {
arr[i][0] = Math.max(arr[i - 1][1] + prices[i], arr[i - 1][0]);
arr[i][1] = Math.max(arr[i - 1][0] - prices[i], arr[i - 1][1]);
}
return arr[prices.length - 1][0];
}Post Views: 317
边栏推荐
- Is it safe to open a dig money account? Is it reliable?
- 3. 整合 Listener
- How do I download videos? Look at the super simple method!
- Keyword long
- APISIX 助力中东社交软件,实现本地化部署
- 【学习笔记】聚类分析
- 字符和整数
- 员工薪资管理系统
- Binary tree problems
- How to analyze the relationship between enterprise digital transformation and data asset management?
猜你喜欢

应用实践 | 10 亿数据秒级关联,货拉拉基于 Apache Doris 的 OLAP 体系演进(附 PPT 下载)

MySQL system error occurred 1067

Alibaba cloud MSE full link grayscale solution practice based on Apache apisik

学习太极创客 — MQTT 第二章(七)ESP8266 MQTT 遗嘱应用

基于 Apache APISIX 的自动化运维平台

Analysis of variance

Query rewriting for opengauss kernel analysis

【Try to Hack】Cobalt Strike(一)

Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer

【笔记:模拟MOS集成电路】带隙基准(基本原理+电流模+电压模电路详解)
随机推荐
题解 The SetStack Computer(UVa12096)紫书P116STL的综合应用
LeetCode每日一题——324. 摆动排序 II
我也差点“跑路”
How to do a good job in customer's successful bottom design | tob Master Course
数据标准化处理
Application of Andy s first dictionary (uva10815) Purple Book p112set
稳定性总结
【学习笔记】主成分分析法介绍
【学习笔记】聚类分析
请问同业存单是否靠谱,安全吗
方 差 分 析
题解 Ananagrams(UVa156)紫书P113map的应用
T-test (test whether the mean difference between the two populations is significant)
[book club issue 13] packaging format of video files
Is it safe for CICC fortune to open an account? Let's talk about CICC fortune
Embedded dynamic Arabic string conversion LCD display string [thanks for Jianguo ambition]
Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer
Why does next() in iterator need to be forcibly converted?
【学习笔记】因子分析
input separator