Last active
December 18, 2022 15:47
-
-
Save charlespunk/4700450 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Say you have an array for which the ith element is the price of a given stock on day i. | |
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int maxProfit(int[] prices) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(prices == null || prices.length == 0) return 0; | |
int min = prices[0]; | |
int max = Integer.MIN_VALUE; | |
for(int i = 0; i < prices.length; i++){ | |
int money = prices[i] - min; | |
if(money > max) max = money; | |
if(prices[i] < min) min = prices[i]; | |
} | |
return max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment