买卖股票的最佳时机
牛客网81
描述
假设你有一个数组prices,长度为n,其中prices[i]是某只股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1. 你可以多次买卖该只股票,但是再次购买前必须卖出之前的股票
2. 如果不能获取收益,请返回0
3. 假设买入卖出均无手续费
数据范围: 1 \le n \le 1 \times 10^51≤n≤1×105 , 1 \le prices[i] \le 10^41≤prices[i]≤104
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
进阶:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
示例1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 计算最大收益 * @param prices int整型一维数组 股票每一天的价格 * @return int整型 */ public int maxProfit ( int [] prices) { // write code here // write code here int [][] dp = new int [prices.length][ 2 ]; dp[ 0 ][ 0 ] = -prices[ 0 ]; dp[ 0 ][ 1 ] = 0 ; for ( int i = 1 ; i < prices.length; i++) { dp[i][ 0 ] = Math.max(dp[i - 1 ][ 0 ], dp[i - 1 ][ 1 ] - prices[i]); dp[i][ 1 ] = Math.max(dp[i - 1 ][ 1 ], dp[i - 1 ][ 0 ] + prices[i]); } return dp[prices.length - 1 ][ 1 ]; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!