File tree 1 file changed +24
-6
lines changed
src/main/java/com/diguage/algorithm/leetcode
1 file changed +24
-6
lines changed Original file line number Diff line number Diff line change 34
34
* @since 2020-01-01 13:01
35
35
*/
36
36
public class BestTimeToBuyAndSellStock {
37
+ /**
38
+ * Runtime: 0 ms, faster than 100.00% of Java online submissions for Best Time to Buy and Sell Stock.
39
+ *
40
+ * Memory Usage: 37.3 MB, less than 100.00% of Java online submissions for Best Time to Buy and Sell Stock.
41
+ */
42
+ public int maxProfit (int [] prices ) {
43
+ int minPrice = Integer .MAX_VALUE ;
44
+ int maxProfit = 0 ;
45
+ for (int i = 0 ; i < prices .length ; i ++) {
46
+ if (prices [i ] < minPrice ) {
47
+ minPrice = prices [i ];
48
+ } else if (prices [i ] - minPrice > maxProfit ) {
49
+ maxProfit = prices [i ] - minPrice ;
50
+ }
51
+ }
52
+ return maxProfit ;
53
+ }
54
+
37
55
/**
38
56
* Runtime: 198 ms, faster than 8.08% of Java online submissions for Best Time to Buy and Sell Stock.
39
57
*
40
58
* Memory Usage: 38.5 MB, less than 76.99% of Java online submissions for Best Time to Buy and Sell Stock.
41
59
*/
42
- public int maxProfit (int [] prices ) {
60
+ public int maxProfitBruteForce (int [] prices ) {
43
61
if (Objects .isNull (prices ) || prices .length < 2 ) {
44
62
return 0 ;
45
63
}
46
- int result = 0 ;
64
+ int maxProfit = 0 ;
47
65
48
66
for (int i = 0 ; i < prices .length - 1 ; i ++) {
49
67
for (int j = i + 1 ; j < prices .length ; j ++) {
50
- int temp = prices [j ] - prices [i ];
51
- if (temp > result ) {
52
- result = temp ;
68
+ int profit = prices [j ] - prices [i ];
69
+ if (profit > maxProfit ) {
70
+ maxProfit = profit ;
53
71
}
54
72
}
55
73
}
56
- return result ;
74
+ return maxProfit ;
57
75
}
58
76
59
77
public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments