# [leetcode] Best Time to Buy and Sell Stock II

### Best Time to Buy and Sell Stock 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).

Tags: array, greedy

1. 如果当前价格大于下一天的价格，开启一次新的交易，当前profit加到sum里，profit清零；

2. 如果当前价格小于下一天的价格，继续本次交易，更新profit的值。

```class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if (n <= 1){
return 0;
}
int sum = 0;
int profit = 0;
int nextPrice = *(prices.end() - 1);
for (int i = n - 2; i >=0; i--){
if (prices[i] > nextPrice){ // start a new transection
sum += profit;
profit = 0;
nextPrice = prices[i];
}
else if (prices[i] <= nextPrice){ // continue this transection
profit += nextPrice - prices[i];
nextPrice = prices[i];
}
}
sum += profit;
return sum;
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.