121. Best Time to Buy and Sell Stock Easy
1/**
2 * [121] Best Time to Buy and Sell Stock
3 *
4 * You are given an array prices where prices[i] is the price of a given stock on the i^th day.
5 * 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.
6 * Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
7 *
8 * Example 1:
9 *
10 * Input: prices = [7,1,5,3,6,4]
11 * Output: 5
12 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
13 * Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
14 *
15 * Example 2:
16 *
17 * Input: prices = [7,6,4,3,1]
18 * Output: 0
19 * Explanation: In this case, no transactions are done and the max profit = 0.
20 *
21 *
22 * Constraints:
23 *
24 * 1 <= prices.length <= 10^5
25 * 0 <= prices[i] <= 10^4
26 *
27 */
28pub struct Solution {}
29
30// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
31// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/?currentPage=1&orderBy=most_votes&query=
32
33// submission codes start here
34use std::cmp;
35
36impl Solution {
37 pub fn max_profit(prices: Vec<i32>) -> i32 {
38 if prices.len() < 2 {
39 return 0;
40 }
41
42 let mut result = 0;
43 let mut previous_min = i32::MAX;
44
45 for p in prices {
46 previous_min = cmp::min(previous_min, p);
47 result = cmp::max(result, p - previous_min);
48 }
49
50 result
51 }
52}
53
54// submission codes end
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn test_121() {
62 assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 5);
63 }
64}
65
Back
© 2025 bowen.ge All Rights Reserved.