Best Time to Buy and Sell Stock II
程序员文章站
2022-05-21 13:23:43
...
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
与第一个股票问题的区别是这里我们可以进行多次交易,我们同样用两个变量,profit用来记录当前交易是否盈利,如果是盈利就加入到总利润max中,如果亏损就继续往下查找。这样只要能盈利的都会记录到max中,代码如下:
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
与第一个股票问题的区别是这里我们可以进行多次交易,我们同样用两个变量,profit用来记录当前交易是否盈利,如果是盈利就加入到总利润max中,如果亏损就继续往下查找。这样只要能盈利的都会记录到max中,代码如下:
public class Solution { public int maxProfit(int[] prices) { int profit = 0; int max = 0; for(int i = 1; i < prices.length; i++) { profit = prices[i] - prices[i - 1]; if(profit > 0) max += profit; } return max; } }
推荐阅读
-
LeetCode_Array_123. Best Time to Buy and Sell Stock III买卖股票的最佳时机III(C++)
-
Leetcode No.121 Best Time to Buy and Sell Stock(c++实现)
-
309. Best Time to Buy and Sell Stock with Cooldown
-
Leetcode 309. Best Time to Buy and Sell Stock with Cooldown
-
[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown
-
【DP + 卖股票】LeetCode 309. Best Time to Buy and Sell Stock with Cooldown
-
LeetCode题解系列--309. Best Time to Buy and Sell Stock with Cooldown
-
动态规划-309. Best Time to Buy and Sell Stock with Cooldown
-
(M)Dynamic Programming:309. Best Time to Buy and Sell Stock with Cooldown
-
309. Best Time to Buy and Sell Stock with Cooldown