形式上,对于每组 i 和j(其中 j>i)我们需要找出 max(prices[j]−prices[i])。
(1)暴力法【超时】
代码
1 2 3 4 5 6 7 8 9 10 11 12 13
//C++ class Solution { public: int maxProfit(vector<int>& prices) { int n = (int)prices.size(), ans = 0; for (int i = 0; i < n; ++i){ for (int j = i + 1; j < n; ++j) { ans = max(ans, prices[j] - prices[i]); } } return ans; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//Java public class Solution { public int maxProfit(int[] prices) { int maxprofit = 0; for (int i = 0; i < prices.length - 1; i++) { for (int j = i + 1; j < prices.length; j++) { int profit = prices[j] - prices[i]; if (profit > maxprofit) { maxprofit = profit; } } } return maxprofit; } }
复杂度分析
时间复杂度:O(n^2^)。循环运行 $\dfrac{n (n-1)}{2} $次。
空间复杂度:O(1)。只使用了常数个变量。
(2)一次遍历
思路及算法
假设给定的数组为:[7, 1, 5, 3, 6, 4]
如果我们在图表上绘制给定数组中的数字,我们将会得到:
我们来假设自己来购买股票。随着时间的推移,每天我们都可以选择出售股票与否。那么,假设在第 i 天,如果我们要在今天卖股票,那么我们能赚多少钱呢?
显然,如果我们真的在买卖股票,我们肯定会想:如果我是在历史最低点买的股票就好了!太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。