题目网址:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2zsx1/
public class Solution {
public int MaxProfit(int[] prices) {
int buyIn=0;
int sellOut=0;
int i,j;
int k=0;
int num=0;
if (prices.Length == 2)
{
if(prices[0] <= prices[1])
{
return prices[1] - prices[0];
}
else
{
return 0;
}
}
for(i=0;i<prices.Length-1;i++){
if(prices[i]<prices[i+1] && k!=1){
buyIn=prices[i];
k++;
}
if(k==1){
for(j=i;j<prices.Length-1;j++){
if(prices[j]>prices[j+1]){
sellOut=prices[j];
k++;
i=j;
break;
}
if(j==prices.Length-2 && k!=2){
sellOut=prices[j+1];
k++;
i=j;
break;
}
}
}
if(k==2){
num+=(sellOut-buyIn);
k=0;
}
}
return num;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/0e4677830a8b56f9c575a8d76e718d5b.png)