Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 18, 2022 15:47
Show Gist options
  • Save charlespunk/4700450 to your computer and use it in GitHub Desktop.
Save charlespunk/4700450 to your computer and use it in GitHub Desktop.
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.
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