LeetCode 121. Best Time to Buy and Sell Stock [Easy]
题目来源:https://leetcode.com/problems/best-time-to-buy-and-sell-stock
题目难度:Easy
题目
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 1:
1 | Input: prices = [7,1,5,3,6,4] |
Example 2:
1 | Input: prices = [7,6,4,3,1] |
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 104
解答1[Java]:
1 | public class Solution { |
思路
使用两个变量,一个存储截至目前最小的值,一个存储截至目前最大的利润。然后对股票价格依次遍历,每遍历到一个元素都更新当前最小值和当前最大利润,等到遍历结束时,取最大利润值即可。
相同题目
LCR 188. 买卖芯片的最佳时机 - 力扣(LeetCode)
剑指 Offer 63:剑指 Offer 63. 股票的最大利润 | 算法通关手册(LeetCode)
关联题目
Best Time to Buy and Sell Stock II - LeetCode