Algorithm(알고리즘)/백준

01. 최대 합 구간을 구하는 함수(Brute Force)

고로케 2021. 5. 16.
반응형

01. 최대 합 구간을 구하는 함수(Brute Force)

풀이 (1)

def sublist_max(profits):
    start = 0
    max_profit = []

    for i in range(0, len(profits)):
        compare = []
        for j in range(i, len(profits)):
            compare.append(profits[j])
            # print(sum(compare))

            if sum(compare) > sum(max_profit):
                max_profit = compare.copy()
                print(max_profit)
                start = profits.index(max_profit[0])

    return sum(max_profit)

# 테스트
print(sublist_max([4, 3, 8, -2, -5, -3, -5, -3]))
print(sublist_max([2, 3, 1, -1, -2, 5, -1, -1]))
print(sublist_max([7, -3, 14, -8, -5, 6, 8, -5, -4, 10, -1, 8]))


# 결과
15
8
27

풀이 (2)

def sublist_max(profits):
    max_profit = profits[0]  # 최대 수익

    for i in range(len(profits)):
        # 인덱스 i부터 j까지 수익의 합을 보관하는 변수
        total = 0

        for j in range(i, len(profits)):
            # i부터 j까지 수익의 합을 계산
            total += profits[j]

            # i부터 j까지 수익의 합이 최대 수익이라면, max_profit 업데이트
            max_profit = max(max_profit, total)

    return max_profit

# 테스트
print(sublist_max([4, 3, 8, -2, -5, -3, -5, -3]))
print(sublist_max([2, 3, 1, -1, -2, 5, -1, -1]))
print(sublist_max([7, -3, 14, -8, -5, 6, 8, -5, -4, 10, -1, 8]))

# 결과
 15
 8
 27

풀이 (1)

풀이 (2)

반응형

댓글