大家觉得写还可以,可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn
122. 买卖股票的最佳时机 II
题目描述
给定一个数组,它的第 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 ^ 4
0 <= prices[i] <= 10 ^ 4
分析
贪心
先将总利润设为0,比较数列中相邻两元素,如果后面的元素大于前面的元素,就把差值加到总利润中,若小于,则放弃本次交易
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i=1;i<prices.length;i++){
int profit = prices[i] - prices[i-1];
if(profit>0) res+=profit;
}
return res;
}
}
单调栈
- 如果新加入元素比栈顶元素小,则栈顶-栈底元素,并将新元素进栈(小细节:循环结束再进行一次
res += (stack[index] - stack[0]),防止新加入元素一直递增,res未存进值。 - 若大于,则直接进栈
class Solution {
public int maxProfit(int[] prices) {
int[] stack = new int[prices.length];
int index = -1;
int res = 0;
for (int i = 0; i < prices.length; i++) {
if (index != -1 && stack[index] > prices[i]) { // remove all the items
if (index != 0) { // stack top - stack bottom
res += (stack[index] - stack[0]);
}
index = -1;
}
stack[++index] = prices[i];
}
res += (stack[index] - stack[0]);
return res;
}
}
提交结果

2020年9月20日更
大家觉得写还可以,可以点赞、收藏、关注一下吧!
也可以到我的个人博客参观一下,估计近几年都会一直更新!和我做个朋友吧!https://motongxue.cn
本文详细解析了股票交易中的两种算法策略:贪心算法和单调栈算法,通过具体实例展示了如何利用这两种算法来计算股票买卖的最佳时机以获取最大利润。

156

被折叠的 条评论
为什么被折叠?



