LeetCode Best Time To Buy And Sell Stock 2


Say you have an array for which the i(th) 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).

The original problem is here.

The original code is here.

My Solution

I solve this problem in C++, as below:

/*Best Time to Buy and Sell Stock II
*Author: shuaijiang
*Email: zhaoshuaijiang8@gmail.com
using namespace std;

class Solution {
    int maxProfit(vector<int>& prices) {
           return 0;
       int profit = 0;

       for(int i=1;i<prices.size();i++){
               int diff = prices[i]-prices[i-1];
                   profit += diff;
           return profit;


To solve the problem, I compute the difference between the current price and the last price. If the difference is non-negative, then add to the profit.