知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 121. Best Time to Buy and Sell Stock (Easy/Python)

코방코 2022. 9. 23. 15:13
728x90
 

Best Time to Buy and Sell Stock - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Above is the link to the problem.

 

Problem

You are given an array prices where prices[i] is the price of a given stock on the i th 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 

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.

 

I solved this problem by the below code.

 

 

There can be exist more lower price than buy price.

But there are cases that is the last price of days.

or case of the price gap is lower.

This is why the code only check the gap of price and lower value.

We can get the new gap when only if there exists selling day and gap of price is bigger than past.

 

 

This code get the top 0.50% of time efficiency and use 25 MB of memory.

 

 

728x90
반응형