当前位置:网站首页>LeetCode121. 买卖股票的最佳时机
LeetCode121. 买卖股票的最佳时机
2022-06-28 20:59:00 【Yuyy】
本文最后更新于 484 天前,其中的信息可能已经有所发展或是发生改变。
一、思路
找出选择和状态
二、问题
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。示例 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。提示:
1 <= prices.length <= 1050 <= prices[i] <= 104
Related Topics
- 数组
- 动态规划
\n
- 1447
- 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(- prices[i], arr[i - 1][1]);
}
return arr[prices.length-1][0];
}Post Views: 225
边栏推荐
- 大智慧上怎么进行开户啊, 安全吗
- LeetCode每日一题——522. 最长特殊序列 II
- 03.hello_ rust
- Employee salary management system
- Data standardization processing
- Leetcode 36. Effective Sudoku (yes, once)
- No module named ‘PyEMD‘ ;使用plt.figure()TypeError: ‘module‘ object is not callable
- SaaS sales upgrade under the new situation | tob Master Course
- Automatic operation and maintenance platform based on Apache APIs
- Characters and integers
猜你喜欢

MongoDB——副本集与分片

CNN-LSTM的flatten

【筆記:模擬MOS集成電路】帶隙基准(基本原理+電流模+電壓模電路詳解)

APISIX 助力中东社交软件,实现本地化部署

Learn Tai Chi maker mqtt Chapter 2 (VIII) esp8266 mqtt user password authentication
![[graduation season · advanced technology Er] hard work can only pass, hard work can be excellent!](/img/e5/b6035abfa7d4bb59c3080d3b87ce45.jpg)
[graduation season · advanced technology Er] hard work can only pass, hard work can be excellent!

Analysis of variance

ref属性,props配置,mixin混入,插件,scoped样式

Bitbucket 使用 SSH 拉取仓库失败的问题

视频号如何下载视频?来看超简单方法!
随机推荐
题解 Ananagrams(UVa156)紫书P113map的应用
Win 10 create a gin framework project
Understanding of incomplete types
No module named ‘PyEMD‘ ; Use plt figure()TypeError: ‘module‘ object is not callable
Apisik helps Middle East social software realize localized deployment
Leetcode daily question - Sword finger offer II 091 Paint the house
with torch. no_ Grad(): reason for using
On the complexity of software development and the way to improve its efficiency
Bitbucket 使用 SSH 拉取仓库失败的问题
pyechart绘制多条y轴折线图
The principle and source code analysis of Lucene index construction
Application of Andy s first dictionary (uva10815) Purple Book p112set
嵌入式中 动态阿拉伯语字符串 转换 LCD显示字符串【感谢建国雄心】
【学习笔记】因子分析
关于不完全类型的认识
API 网关 Apache APISIX 助力雪球双活架构演进
[graduation season · advanced technology Er] hard work can only pass, hard work can be excellent!
Globalsign's Pan domain SSL certificate
穩定性總結
我也差点“跑路”