[leetcode]123. Best Time to Buy and Sell Stock III 最佳炒股时机之三

本文介绍了一种算法,用于寻找股票买卖的最佳时机,允许进行最多两次交易。通过将数组分为两部分,每部分进行一次交易,算法计算了从第0天到第i天的最大利润f(i),以及从第i天到最后一天的最大利润g(i)。最终返回f(i)和g(i)之和的最大值作为最大利润。

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 at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

 

题目

和之前一样,这次你至多能买卖两次。

 

思路

1. Split the array into two parts, one trade each.

2. Say that f(i) stands for max profit in [0,i] , g(i) stands for max profix in [i, n-1] , then update and finally return max(f(i) + g(i))

 

代码

 1 // Best Time to Buy and Sell Stock III
 2 // 时间复杂度O(n),空间复杂度O(n)
 3 public class Solution {
 4     public int maxProfit(int[] prices) {
 5         if (prices.length < 2) return 0;
 6 
 7         final int n = prices.length;
 8         int[] f = new int[n];
 9         int[] g = new int[n];
10 
11         for (int i = 1, valley = prices[0]; i < n; ++i) {
12             valley = Math.min(valley, prices[i]);
13             f[i] = Math.max(f[i - 1], prices[i] - valley);
14         }
15 
16         for (int i = n - 2, peak = prices[n - 1]; i >= 0; --i) {
17             peak = Math.max(peak, prices[i]);
18             g[i] = Math.max(g[i], peak - prices[i]);
19         }
20 
21         int max_profit = 0;
22         for (int i = 0; i < n; ++i)
23             max_profit = Math.max(max_profit, f[i] + g[i]);
24 
25         return max_profit;
26     }
27 }

 

转载于:https://www.cnblogs.com/liuliu5151/p/10042110.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值