LeetCode OJ:Best Time to Buy and Sell Stock II(股票买入卖出最佳实际II)

时间:2023-03-09 19:38:16
LeetCode OJ:Best Time to Buy and Sell Stock II(股票买入卖出最佳实际II)

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).
对贪心不是很了解,这题跟上一个类似的题目相差还是有点大的,没想出来,看了别人的实现。实际上思路很简单,只要一直在涨就不动,一旦发现跌了之后就将前一个值记录下来之后求出与买入时候的差值,重复进行下一轮的买入以及卖出,代码如下:

 class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if(!sz) return ;
int profit = ;
int start = ;
for(int i = ; i < sz; ++i){
if(prices[i] >= prices[i - ])
continue;
profit += prices[i - ] - prices[start];
start = i;
}
profit += prices[sz - ] - prices[start];
return profit;
}
};