122. 买卖股票的最佳时机 II&&738. 单调递增的数字

买入股票的时机,就是后一天的价比今天的价格高才买入;
卖出的条件是今天的价格比明天的价格低,卖出的同时也买入第二天的股票。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        '''
        在右数大于左数时选择右数买入,在左数卖出

        '''
        profit = 0
        flag = True
        global i
        if len(prices)<2:return 0   
        #首先得先找到第一天购买的时间点
        for i in range(len(prices)-1):
            if prices[i] < prices[i+1]:
                inp = prices[i]
                break
            if i == len(prices)-2:
                return 0
        #后续每次买进卖出都可以同时进行
        for j in range(i,len(prices)-1,1):
            end_ = False
            if prices[j] > prices[j+1]:
                profit += prices[j]-inp
                inp = prices[j+1]
                end_ = True
        if end_ == False:
            profit += prices[-1]-inp
        return profit

将输入的数字转化为字符串,采用谈心法求解,先遍历出前一数大于后一个数的指针位置,后又将此指针向前移动之至前一个数和它不相等的位置,此时指针所指的位置通过阿西克码转换得到小于1的数字,后面数字全部改为9即可。

class Solution:
    def monotoneIncreasingDigits(self, N: int) -> int:
        t=str(N)
        flag = True
        com = True
        for i in range(len(str(N))-1):
            if int(t[i]) > int(t[i+1]):
                flag = False
                break
            
        if flag == False:
            for j in range(i,0,-1):
                if t[j] != t[j-1]:
                    com = False
                    break
            if com == False:
                res = int(t[0:j] + chr(ord(t[j])-1) + '9'*(len(t)-j-1))
            else:   #前面全部是相同的情况
                res = int(chr(ord(t[0])-1) + '9'*(len(t)-1)) 
        else:
            res = N
        return res

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值