LeetCode 之 Best Time to Buy and Sell Stock

题目为:Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

本题的宗旨在算一个最大差值,开始想的是用一个min和max分别记录数组中的最大和最小值,当然,现实是无情的,wrong answer,仔细想了一下,因为买卖股票有个时间的问题,卖的时候必须在买之前,因此上种方法有错。

正确解法:

1,声明两个int,一个profit,一个min,分别记录当前最小的price和最大的profit

     用一个值来记录最小的值,profit永远都是由当前最大的减去当前最小的,因此关键在于,当浏览数组的时候,遇到比max更大的要及时更换,而遇到比min小的值时,要谨慎(只更新min,不更新profit)因为当前的min是买入点,你永远不知道买了股票之后是否有更适合的卖出点,因此:遇到max时,及时更换max的值(我用的是更换profit,不过宗旨一样),遇到比min更小的时,不更新profit,只把min存起来,以后每次判别时,要判断两个值,1.prices[i]是否是最小的值,2.当前值与已知的min产生的profit是否是更大的profit


 int maxProfit(vector<int> &prices) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int profit=0;
        //int min=0;
        
        if(prices.size()<2){
            return 0;
        }
        
        int min = prices[0];
        
        for (int i = 1; i < prices.size();i++){
            if (prices[i]<min  ){
                min = prices[i];
                continue;
            }
            
            if(prices[i] - min > profit){
                profit = prices[i] - min;
            }
            
        }
        
        return profit;
    }


--------更新

看了这个题的第三季,有了新的代码,比上次的易懂

思想:每次查看当前与min的差值(diff),当这个diff大于当前的profit,更新profit;当diff小于0,说明遇到了更小的min,更新min就可以

代码如下(48ms):

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int profit=0;
       
        if(prices.size()<2){
            return 0;
        }
        
        int min = prices[0];
        
        for (int i = 1; i < prices.size();i++){
            //记录当前值与当前最小的差
            int diff = prices[i] - min;
            //差大于profit时,更新profit
            if (diff>profit){
                profit = diff;
            }
            //差小于0时,说明当前数值比min更小,更新min
            else if(diff < 0){
                min = prices[i];
            }
            
        }
        
        return profit;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值