121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
题目大致意思:
给你一个数组代表股票每日的价格,你最多可以交易一次股票价格(可以不交易), 只能按照先买入后卖出的的顺序交易。求出最大的股票交易获利
解题思路:
主要方法:动态规划 设dp[i] 表示第i天交易获利的值, 其中 dp[0] = 0 (第一天交易或者不交易都为0 一天内股价不变)
min 代表第一天开始到第i天的最低股票价格. 我们只需要维护这个dp数组 便可求解.
分析: 每日的股价分为如下三种种情况
(1) 今日股价大于昨日股价考虑交易 交易获利:prices[i] - min, 昨日获利 dp[i-1] 取两者的最大值
dp[i] = Math.max( dp[i-1], prices[i] - min);
(2) 今日估计小于昨日股价 不交易(傻瓜才会交易) 即 按照昨日的股价作为最大的获利
dp[i] = dp[i-1];
(3) 今日股价等于昨日股价 : 交易或者不交易 与昨日收益一样 同(2)
dp[i] = dp[i-1];
附上代码 :
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int[] dp = new int[prices.length];
dp[0] = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i ++){
if(min > prices[i]) min = prices[i];
if(prices[i] > prices[i-1]){
dp[i] = Math.max( dp[i-1], prices[i] - min);
}else {
dp[i] += dp[i-1];
}
}
return dp[prices.length-1];
}
注: 限作者水平有限,有任何问题欢迎评论区留言或者私信。欢迎幸福的骚扰