3月打卡活动第9天 LeetCode第121题:买卖股票的最佳时机(简单)

3月打卡活动第9天 LeetCode第121题:买卖股票的最佳时机(简单)

  • 题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
    在这里插入图片描述
  • 解题思路:双指针,左指针记录最小值,右指针依次后移
class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if(len==0) return 0;
        int left = 0;
        int right = 1;
        int max = 0;
        while(right<len){
            if(prices[left]>=prices[right]){
                left = right;
                right = left+1;
            }else{
                if(prices[right]-prices[left]>max){
                    max = prices[right]-prices[left];
                }
                right++;
            }
        }
        
        return max;
    }
}

在这里插入图片描述

  • 题解做法:只用了一个变量
public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice)
                minprice = prices[i];
            else if (prices[i] - minprice > maxprofit)
                maxprofit = prices[i] - minprice;
        }
        return maxprofit;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了100 篇原创文章 · 获赞 12 · 访问量 2359

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104746950