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.
'Code > LeetCode' 카테고리의 다른 글
[LeetCode] 136. Single number (Easy/Python) (0) | 2022.09.26 |
---|---|
[LeetCode] 125. Valid Palindrome (Easy/Python) (0) | 2022.09.25 |
[LeetCode] 88. Merge Sorted Array (Easy/Python) (0) | 2022.09.17 |
[LeetCode] 70. Climbing Stairs (Easy/Python) (0) | 2022.09.15 |
[LeetCode] 67. Add Binary (Easy/Python) (0) | 2022.09.08 |