本题来自:力扣-面试经典 150 题
面试经典 150 题 - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台https://leetcode.cn/studyplan/top-interview-150/
题解:
class Solution {
public int maxProfit(int[] prices) {
int key = prices[0];
int result = 0;
for(int i = 0;i < prices.length;i++){
if(key > prices[i]){
key = prices[i];
}else{
int diff = prices[i] - key;
key = prices[i];
result += diff;
}
}
return result;
}
}
思路如下:
与上一道题不同的是,本题可以多次买入,求总共利润
1. 遍历数组:
1.1 当key大于下一个数字的时候,卖出是亏损的,所以直接将key替换为下一个数(在下一天买入)
1.2 当key小于下一个数字的时候,卖出是赚的,直接卖出,并且再买入(将key替换为下一个数)
2.返回结果
综上所述:代码可以简写为
class Solution {
public int maxProfit(int[] prices) {
int key = prices[0];
int result = 0;
for(int i = 0;i < prices.length;i++){
if(key < prices[i])
result += (prices[i] - key);
key = prices[i];
}
return result;
}
}