[Leet Code] #2 Best Time to Buy and Sell Stock (Python3)

Jin·2022년 10월 20일
0

Leet Code

목록 보기
1/2
post-thumbnail

https://leetcode.com/problems/sum-of-two-integers/

문제

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

1 <= prices.length <= 105
0 <= prices[i] <= 104

풀이

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        max_profit = -10001
        for i in range(0,len(prices)):
            for j in range(i+1,len(prices)):
                profit = prices[j]-prices[i]
                if max_profit <= profit:
                    max_profit = profit
            if max_profit < 0:
                #prices.pop(0)
                i+=1
        if max_profit < 0:
            max_profit = 0
        return max_profit

결과 : log n^2 이중 for문 사용으로 인한 시간 초과

profile
A journey of a thousand miles begins with a single step

0개의 댓글