《中英双解》leetCode 121 Best Time to buy and sell

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

对于这种求最值得问题可以使用动态规划,贪心算法等等方法来计算,不过,对于那方面我还没有系统得学习,就先不用那些方法了,现在先来看看暴力和双指针法。

关于暴力法提交得时候会超时,不过我们需要得是掌握这种思想,哪种思想呢?

我们来看看这一题,总的来说就是给你一个无序数组,让你依次遍历两个数,并求取最值,这个时候大家第一反应肯定就是遍历,因为关于数组这些简单题中的解题方法就是那几种,我目前遇到的有双指针法,遍历,暴力匹配,动态规划,还有哈希,递归等等。这一题困扰我们的应该就是如何去求那个最值,先看暴力法。

class Solution {
    public int maxProfit(int[] prices) {
        // //暴力匹配,不过这种方法超时了
        // int max = 0;
        // for(int i = 0;i < prices.length;i++){
        //     for(int j = i + 1;j < prices.length;j++){
        //         int nowPrice = prices[j] - prices[i];//得到一次循环的最大利润
        //         if(nowPrice > max){
        //             max = nowPrice;  
        //         }
        //     }
        // }
        // return max;
        }
}

 大家应该都能看懂,给一个假定的初始最大值,然后每次遍历进行比较。

再看看双指针。

class Solution {
    public int maxProfit(int[] prices) {
       
        
        //我们再用双指针法来看看,这道题的主要思想我们之前也遇到果,就是一组数组之间的遍历,求取最值
        int slow = 0;
        int fast = 1;
        int max = 0;
        while(fast < prices.length){
            if(prices[fast] < prices[slow]){
                slow = fast;//也就是sslow++
            } else {
                max = Math.max(prices[fast] - prices[slow],max);
            }
            fast++;
        }
        return max;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值