一、题目
给你一个整数数组
prices
,其中prices[i]
表示某支股票第i
天的价格。在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
二、思路
- 题目第二条实际上就是迷惑人的,现在想想,如果这个数组为[1, 5, 4, 2, 6],你根本不用考虑是不是应该第一天买,最后一天卖,因为最大收益永远不会这么取;
- 一降就买一升就卖才是最赚钱的,只用考虑一有收益就保存即可,见解法一;
三、解法
解法一
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int total = 0;
for (int i = 1; i < len; i++) {
if (prices[i] > prices[i - 1]) {
total += prices[i] - prices[i - 1];
}
}
return total;
}
}