力扣初级算法2

怎么大年纪了才开始学习Python,是不是有点儿晚了?但还是挺喜欢敲代码的感觉。看了python有几天了,开始刷力扣的题,在这里记录一下自己的学习过程,和代码。希望大伙提提意见,帮我找出代码中不足之处,让我能够进步快点儿,另外也给同样开始刷题的小伙伴一个参考。(代码已通过测试)(本人现在使用Labview开发测试设备的软件,有懂的小伙伴可以给我留言交流啊)

 代码如下:

#coding:utf-8
#力扣初级算法第二题:买卖股票的最佳时机
#测试数据
n = [1,2,3,4,5]
m = [3,1,5,7,2]
q = [5,4,3,2,1]
p = [2]
x = [0,3,8,6,8,6,6,8,2,0,2,7]
#测试代码
def maxProfit(prices):
    buy = []
    sell = []
    rich = 0
    #数据处理
    #在输入的数据中相邻数据如果相等,是没有必要的,需要去除其中一个,本程序定义去除前面的数据
    removelist = []     #存放输入数据中需要去除的元素的索引
    temp = 0            #中间变量
    #找到需要去除的元素的索引,将其放入removelist列表中
    #因为要输出的元素在原列表中不止一个,而我们想要删除的是特定位置的元素,所以不能使用remove方法
    for i in range(len(prices)-1):
        if prices[i] == prices[i+1]:
            removelist.append(i)
    #print(removelist)
    #去除元素
    for i in removelist:
        prices.pop(i-temp)  #pop方法:删除列表中指定位置的元素
        #因为列表中某个元素被删除后,列表长度将变短1
        temp += 1
    #print(prices)

    #找到所有可购买的点
    if len(prices) <= 1:    #如果输入只有一个数据或没有数据,就没有购买的必要
        return 0
    else:
        #从第一个元素开始,到倒数第二个元素为止,因为最后一定不能买入
        #买入一定比卖出价格低,所以先找满足prices[i]<prices[i+1]的元素
        #然后,判断i值:如果i==0,则prices[i]是一个买入点,将其放入buy列表;如果i>0,则需要判断prices[i]<prices[i-1]
        #如果满足,则buy.append(prices[i]);若不满足continue
        for i in range(len(prices)-1):
            if prices[i] < prices[i+1]:
                if i == 0:
                    buy.append(prices[i])
                else:
                    if prices[i] < prices[i-1]:
                        buy.append(prices[i])
                    else:
                        continue
    #print(buy)
    #找到所有可卖出点
    #卖出点一定是从第二个元素开始
    for j in range(1,len(prices)):
        #如果没有买入,则收入为0
        if len(buy) == 0:
            return 0
        else:
            if j < len(prices)-1:
                if prices[j-1] <= prices[j] and prices[j] >= prices[j+1]:
                    sell.append(prices[j])
            else:
                if prices[j] >= prices[j-1]:
                    sell.append(prices[j])

    #print(sell)
    for i in range(len(buy)):
        rich += (sell[i] - buy[i])

    return rich

print(maxProfit(n))
print(maxProfit(m))
print(maxProfit(p))
print(maxProfit(q))
print(maxProfit(x))
原创文章 24 获赞 45 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weilixin88/article/details/86547782