题解
方法1:求差预处理+求最大子序和
主要思路
这个问题我们算当天买入第二天卖出会获利多少,随后再求连续N天买入卖出收益最大值即可。
源代码:c++
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() < 2)
return 0;
for(int i = prices.size() - 1; i > 0; i--)
{
prices[i] = prices[i] - prices[i - 1];
}
int getted = 0;
int max_getted = 0;
for(int i = 1; i < prices.size(); i++)
{
getted += prices[i];
if(getted < 0)
getted = 0;
if(getted > max_getted)
{
max_getted = getted;
}
}
return max_getted;
}
};
时空复杂度
- 用时:100 ms, 在所有 C 提交中击败了70.56%的用户
- 内存:91.1 MB, 在所有 C 提交中击败了68.53%的用户
中途错误记录
- return数据错误 return getted 改为 return max_getted
方法2:
主要思路
- 记录【今天之前买入的最小值】
- 计算【今天之前最小值买入,今天卖出的获利】,也即【今天卖出的最大获利】
- 比较【每天的最大获利】,取最大值即可
源代码
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1)
return 0;
int min = prices[0], max = 0;
for(int i = 1; i < prices.length; i++) {
max = Math.max(max, prices[i] - min);
min = Math.min(min, prices[i]);
}
return max;
}
}
执行用时 : 2 ms, 在Best Time to Buy and Sell Stock的Java提交中击败了95.29% 的用户
内存消耗 : 36.1 MB, 在Best Time to Buy and Sell Stock的Java提交中击败了97.97% 的用户