Skip to content

Commit 591ba9b

Browse files
committed
Added 'Best Time to Buy and Sell Stock'
1 parent 0790343 commit 591ba9b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Best Time to Buy and Sell Stock.java

+39
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,45 @@
22

33
class Solution {
44

5+
public int mySolution(int[] prices) {
6+
7+
/*
8+
* SIDE NOTE: This is the solution that I came up with :)
9+
* IMPORTANT: It really helps to create a graph and understand it from a non-programming perspective.
10+
* Do what you normally do when trading stocks, buy low and sell high :)
11+
*
12+
* Time Complexity: O(n) where n = length of input list. The list iterated once
13+
*
14+
* Space Complexity: O(1) because no additional dynamic data structure was created
15+
*/
16+
17+
// If there's only 1 price inside list, then you can't make a profit
18+
if (prices.length <= 1) {
19+
return 0;
20+
}
21+
22+
int maxProfit = 0;
23+
24+
// Set 1st price as buying price and iterate list
25+
int buyingPrice = prices[0];
26+
for (int i = 1; i < prices.length; i++) {
27+
28+
// Set ith element as selling price
29+
int sellingPrice = prices[i];
30+
31+
// If sellingPrice - buyingPrice >= 0, update maxProfit
32+
// If not, then update buyingPrice to the newest smallest price
33+
if (buyingPrice <= sellingPrice) {
34+
maxProfit = Math.max(maxProfit, sellingPrice - buyingPrice);
35+
}
36+
else {
37+
buyingPrice = prices[i];
38+
}
39+
}
40+
41+
return maxProfit;
42+
}
43+
544
public int solution1(int[] prices) {
645

746
int smallestPrice = Integer.MAX_VALUE;

0 commit comments

Comments
 (0)