File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 2
2
3
3
class Solution {
4
4
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
+
5
44
public int solution1 (int [] prices ) {
6
45
7
46
int smallestPrice = Integer .MAX_VALUE ;
You can’t perform that action at this time.
0 commit comments