File tree Expand file tree Collapse file tree 1 file changed +24
-6
lines changed
src/main/java/com/diguage/algorithm/leetcode Expand file tree Collapse file tree 1 file changed +24
-6
lines changed Original file line number Diff line number Diff line change 3434 * @since 2020-01-01 13:01
3535 */
3636public 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+
3755 /**
3856 * Runtime: 198 ms, faster than 8.08% of Java online submissions for Best Time to Buy and Sell Stock.
3957 *
4058 * Memory Usage: 38.5 MB, less than 76.99% of Java online submissions for Best Time to Buy and Sell Stock.
4159 */
42- public int maxProfit (int [] prices ) {
60+ public int maxProfitBruteForce (int [] prices ) {
4361 if (Objects .isNull (prices ) || prices .length < 2 ) {
4462 return 0 ;
4563 }
46- int result = 0 ;
64+ int maxProfit = 0 ;
4765
4866 for (int i = 0 ; i < prices .length - 1 ; i ++) {
4967 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 ;
5371 }
5472 }
5573 }
56- return result ;
74+ return maxProfit ;
5775 }
5876
5977 public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments