122. Best Time to Buy and Sell Stock II Medium

@problem@discussion
#Array#Dynamic Programming#Greedy



1/**
2 * [122] Best Time to Buy and Sell Stock II
3 *
4 * You are given an integer array prices where prices[i] is the price of a given stock on the i^th day.
5 * On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
6 * Find and return the maximum profit you can achieve.
7 *  
8 * Example 1:
9 * 
10 * Input: prices = [7,1,5,3,6,4]
11 * Output: 7
12 * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
13 * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
14 * Total profit is 4 + 3 = 7.
15 * 
16 * Example 2:
17 * 
18 * Input: prices = [1,2,3,4,5]
19 * Output: 4
20 * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
21 * Total profit is 4.
22 * 
23 * Example 3:
24 * 
25 * Input: prices = [7,6,4,3,1]
26 * Output: 0
27 * Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
28 * 
29 *  
30 * Constraints:
31 * 
32 * 	1 <= prices.length <= 3 * 10^4
33 * 	0 <= prices[i] <= 10^4
34 * 
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
39// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44    pub fn max_profit(prices: Vec<i32>) -> i32 {
45        0
46    }
47}
48
49// submission codes end
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_122() {
57    }
58}
59


Back
© 2025 bowen.ge All Rights Reserved.