Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active November 8, 2018 19:21
Show Gist options
  • Save dmnugent80/ecc5042604497ae8c3c6 to your computer and use it in GitHub Desktop.
Save dmnugent80/ecc5042604497ae8c3c6 to your computer and use it in GitHub Desktop.
Best Time to Buy and Sell Stock
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