Является ли сложность первого кода O (n), а второго кода O (n ^ 2)? - PullRequest
0 голосов
/ 05 апреля 2020

это первый код

def Maximum__profit_more_efficient(list): # this function count the maximum_profit of specific stock.

    selling_date = 0
    buying_date =  0


    for i in range(len(list)):

        if list[i] > list[selling_date]:
            selling_date = i



    for j in range(len(list)):

        if list[j] < list[buying_date] and j <= selling_date:

            buying_date = j

        elif  j > selling_date:
            break



    print(list[selling_date] -  list[buying_date])

это второй код

def brute_force(list):  
# this function count the maximum_profit of specific stock, but with higher complexity    
    selling_date = 0
    buying_date =  0

    i = 0
    j = 0
    exit = False

    while exit == False:
        if list[i] > list[selling_date]:
            selling_date = i

        if  i < len(list):
            i = i + 1


        if i == len(list):

            while j < len(list):
                if list[j] < list[buying_date] and j <= selling_date:
                    buying_date = j

                j = j + 1
                if j == len(list):
                    exit = True



    print(list[selling_date] -  list[buying_date])    

1 Ответ

1 голос
/ 05 апреля 2020

Сложность первого кода - O (n), как вы уже догадались. Но сложность второго кода также O (n). Несмотря на то, что во втором коде есть вложенный l oop, поскольку значение j устанавливается равным 0 только один раз за пределами циклов, сложность времени составляет только O (n).

...