买卖股票的最佳时机

很容易就去使用双while循环去暴力求解了。
image.png
我觉得,有点像贪心的思路?

  1. var maxProfit = function(prices) {
  2. let minPrice = Infinity;
  3. let maxProfit = 0
  4. for (let i = 0; i < prices.length; i++) { // 假如在第i天卖出,那么要找出之前的最小值
  5. if (minPrice > prices[i]) {
  6. minPrice = prices[i];
  7. } else if (maxProfit < prices[i] - minPrice) {
  8. maxProfit = prices[i] - minPrice;
  9. }
  10. }
  11. return maxProfit
  12. };

122. 买卖股票的最佳时机 II

虽然标着中等难度,其实非常简单:把所有挣钱的阶段都找出来,然后求和即可。

  1. var maxProfit = function(prices) {
  2. let result = [];
  3. let profit = 0;
  4. let sum = 0;
  5. for (let i = 1; i < prices.length; i++) {
  6. profit = prices[i] - prices[i - 1];
  7. if (profit > 0) {
  8. sum += profit
  9. }
  10. }
  11. return sum;
  12. };

股票系列 还有很多,但是这篇文章,这个不是重点。

162. 寻找峰值

image.png
没有这个提示,或者说是题目要求这道题要复杂很多的。
思路:寻找什么东东,模式匹配 => 二分查找。