Last active
November 8, 2018 19:21
-
-
Save dmnugent80/ecc5042604497ae8c3c6 to your computer and use it in GitHub Desktop.
Best Time to Buy and Sell Stock
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
import java.lang.Math; | |
public class Solution { | |
public int maxProfit(int[] prices) { | |
if (prices.length <= 1) return 0; | |
int minPrice = prices[0]; | |
int maxSoFar = Integer.MIN_VALUE; | |
int profitSoFar = Integer.MIN_VALUE; | |
for (int i = 1; i < prices.length; i++){ | |
profitSoFar = prices[i] - minPrice; | |
minPrice = Math.min(minPrice, prices[i]); | |
maxSoFar = Math.max(profitSoFar, maxSoFar); | |
} | |
return Math.max(maxSoFar, 0); | |
} | |
} | |
//variation, can buy and sell multiple times | |
public class Solution { | |
public int maxProfit(int[] prices) { | |
if (prices.length <= 1) return 0; | |
int maxSoFar = 0; | |
int profitCurrent = 0; | |
for (int i = 1; i < prices.length; i++){ | |
profitCurrent = prices[i] - prices[i-1]; | |
if (profitCurrent > 0){ | |
maxSoFar += profitCurrent; | |
} | |
} | |
return Math.max(maxSoFar, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment