贪心算法就是比较短视,只看当前的最优解,不从整体上来考虑。
这个题目时这个样子滴。
贪心算法的思路就是今天和明天只要赚钱我们就买入卖出,赚一天是一天。涨了就买,跌了就不买了。 就是每次抄底买入,到最高卖出的思路。
C++代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
int ans = 0;
for(int i = 0;i < prices.size()-1;i++){
ans = prices[i+1]-prices[i];
if(ans>0){
profit = profit + ans;
}
}
return profit;
}
};
python代码
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
ans = 0
for i in range(len(prices)-1):
ans = prices[i+1]-prices[i]
if ans > 0:
profit = profit + ans
return profit