Skip to content

Commit d854c5c

Browse files
committed
Added Best Time to Buy and Sell Stock II
1 parent b1b820c commit d854c5c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/// You are given an integer array `prices` where `prices[i]` is the price of a
2+
/// given stock on the `ith` day.
3+
///
4+
/// On each day, you may decide to buy and/or sell the stock. You can only hold
5+
/// at most one share of stock at any time. However, you can buy it then
6+
/// immediately sell it on the same day.
7+
///
8+
/// Find and return the maximum profit you can achieve.
9+
struct Solution;
10+
11+
impl Solution {
12+
13+
pub fn max_profit(prices: Vec<i32>) -> i32 {
14+
let n = prices.len();
15+
let mut result = 0;
16+
let mut previous = prices[0];
17+
18+
for i in 1..n {
19+
let today = prices[i];
20+
let diff = today - previous;
21+
if diff > 0 {
22+
result += diff;
23+
}
24+
previous = today;
25+
}
26+
27+
result
28+
}
29+
30+
}
31+
32+
#[cfg(test)]
33+
mod tests {
34+
use super::Solution;
35+
36+
#[test]
37+
fn exmaple_1() {
38+
let prices = vec![7,1,5,3,6,4];
39+
let result = Solution::max_profit(prices);
40+
assert_eq!(result, 7);
41+
}
42+
43+
#[test]
44+
fn example_2() {
45+
let prices = vec![1,2,3,4,5];
46+
let result = Solution::max_profit(prices);
47+
assert_eq!(result, 4);
48+
}
49+
50+
#[test]
51+
fn example_3() {
52+
let prices = vec![7,6,4,3,1];
53+
let result = Solution::max_profit(prices);
54+
assert_eq!(result, 0);
55+
}
56+
57+
}

0 commit comments

Comments
 (0)