个人思路:一开始理解错了,以为只能买卖两次。随后改用贪心算法,总结起来就一句话,遇到有得赚的就卖,有钱就拿了再说。卖了股票之后,记得把start改成卖出的日子,往后继续找有没有钱赚
C
int judge_max(int a, int b){
if(a<=b){
return b;
}
return a;
}
int maxProfit(int* prices, int pricesSize) {
int money = 0;
int start = 0;
for(int i=0;i<pricesSize;i++){
if(prices[i]<=prices[start]){
start = i;
}
else{
money += prices[i]-prices[start];
start = i;
}
}
return money;
}
python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
money=0
start=0
for i in range(0, len(prices)):
if prices[i]>prices[start]:
money += prices[i]-prices[start]
start = i
return money
java
class Solution {
public int maxProfit(int[] prices) {
int money = 0;
int start = 0;
for(int i=0;i<prices.length;i++){
if(prices[i]<=prices[start]){
start = i;
}
else{
money += prices[i]-prices[start];
start = i;
}
}
return money;
}
}