# My 1ms Solution for 122. Best Time to Buy and Sell Stock II

• ``````public class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
if (length < 2) {
return 0;
}
int profit = 0;
for (int i = 1; i < length; i++) {
profit = prices[i] - lastBuy + profit;
}
}
return profit;
}
}``````

• It's clear and efficient

• I feel confused about this requirement: you may not engage in multiple transactions at the same time(ie, you must sell the stock before you buy again). Does this mean you CAN sell and buy at the same day? For example, [1,2,3,4] is the price for day 0~3. So can we buy at 1 and sell at 2, then buy at 2 and sell at 3, then buy at 3 and sell at 4? I think your algorithm is somewhat like this, correct? p.s.: the runtime is 2ms.

• process1: buy at 1 and sell at 2,then buy at 2 and sell at 3,then buy at 3 and sell at 4
process2: buy at 1 and sell at 4,ignore 2 and 3
As we can see,process1 has the same outcome with process2.I think sell and buy at the same day is equal to ingore this day,and maybe he use this point.

• The question tell us that you can buy and sell the stock at the same time.The benefits come to you when you sell some stock.You sell ,you gain.But before you can sell the stock you have some stock.So when the stock you buy last day is cheaper than the one today,there is no benefit for you.So the tactics is selling when you gain and buying when you can gain.ps: my runtime is 1ms,it's real.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.