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
2
3
4
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:

1
2
3
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

解答1[Java]:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public int maxProfit(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
}

思路

使用两个变量,一个存储截至目前最小的值,一个存储截至目前最大的利润。然后对股票价格依次遍历,每遍历到一个元素都更新当前最小值和当前最大利润,等到遍历结束时,取最大利润值即可。

相同题目

LCR 188. 买卖芯片的最佳时机 - 力扣(LeetCode)

剑指 Offer 63:剑指 Offer 63. 股票的最大利润 | 算法通关手册(LeetCode)

关联题目

Best Time to Buy and Sell Stock II - LeetCode

参考资料

  1. 剑指 Offer 63. 股票的最大利润 | 算法通关手册(LeetCode)