题目:
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
解题思路:
解决这题我的思路是这样的,我想用贪心算法解决这一问题。即从原点开始找寻股票上升的时间,然后再找出股票上升幅度最大的时间点,之后把这两个时间点的价格相减即可。
class Solution {
public int maxProfit(int[] prices) {
int index = 0;
int total = 0;
int length = prices.length-1;
for(int i = 0;i<length;i++){
//找到股票上升的起点
while(index<length&&prices[index]>=prices[index+1]){
index++;
}
//不断往前找找到增幅最大的地方
int min = prices[index];
while(index<length&&prices[index]<=prices[index+1]){
index++;
}
int max = prices[index];
total+=(max-min);
}
return total;
}
}
出处:
作者:LeetCode
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2zsx1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。