剑指 Offer(第2版)面试题 63:股票的最大利润
剑指 Offer(第2版)面试题 63:股票的最大利润
题目来源:
解法1:暴力
这样写在 AcWing 能过,在 LeetCode 会超时。
代码:
class Solution
{
public:
int maxDiff(vector<int> &nums)
{
if (nums.empty())
return 0;
int n = nums.size();
int ans = 0;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
ans = max(ans, nums[j] - nums[i]);
return ans;
}
};
复杂度分析:
时间复杂度:O(n2),其中 n 是数组 nums 的元素个数。
空间复杂度:O(1)。
解法2:动态规划
用一个 dp 数组记录历史股价的最低值。
代码:
// 动态规划
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
// 特判
if (prices.size() <= 1)
return 0;
int n = prices.size(), max_profit = 0;
// dp[i] 表示截止到第 i 天,股票价格的最低点
vector<int> dp(n, 0); // 状态数组
dp[0] = prices[0]; // 初始化
// 状态转移
for (int i = 1; i < n; i++)
{
dp[i] = min(dp[i - 1], prices[i]);
max_profit = max(max_profit, prices[i] - dp[i]);
}
return max_profit;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是数组 nums 的元素个数。
空间复杂度:O(n),其中 n 是数组 nums 的元素个数。
空间优化:
// 空间压缩
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
// 特判
if (prices.size() <= 1)
return 0;
int n = prices.size(), low_price = prices[0], max_profit = 0;
// 状态转移
for (int i = 1; i < n; i++)
{
low_price = min(low_price, prices[i]);
max_profit = max(max_profit, prices[i] - low_price);
}
return max_profit;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是数组 nums 的元素个数。
空间复杂度:O(1)。