今天的題目為122.Best Time to Buy and Sell Stock II,這次的題目為前一題的衍生,給一個整數陣列prices,其中prices[i]表示第i天某支股票的價格。你每天都可以選擇買入和/或賣出股票,但你最多只能持有一股股票。你可以在同一天賣出後再買入,只要你在任何時刻都不持有超過一股股票,找出你能夠獲得的最大利潤。
以下為程式碼:
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
}