Skip to content

Instantly share code, notes, and snippets.

@carlosmuvi
Last active January 18, 2018 20:01
Show Gist options
  • Save carlosmuvi/08f2e49f8c3f178f4c90b29ecabe557a to your computer and use it in GitHub Desktop.
Save carlosmuvi/08f2e49f8c3f178f4c90b29ecabe557a to your computer and use it in GitHub Desktop.
public int maxProfit(int[] a) {
if (a.length <= 2) {
return 0;
}
int currentMin = a[0];
int currentMaxProfit = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < currentMin) {
currentMin = a[i];
} else {
int tempProfit = a[i] - currentMin;
if (tempProfit > currentMaxProfit) {
currentMaxProfit = tempProfit;
}
}
}
return currentMaxProfit;
}
//Solution 1: Sieve of Eratosthenes
public int primeNumbers(int a) {
// create an array where true means the number is prime. All are considered prime at the beginning.
boolean[] primesList = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
primesList[i] = true;
}
// mark non-primes
for (int factor = 2; factor * factor <= n; factor++) {
// if factor is prime, then mark multiples of factor as nonprime
if (primesList[factor]) {
for (int j = factor; factor * j <= n; j++) {
primesList[factor * j] = false;
}
}
}
// count primes in the list.
int numberOfPrimes = 0;
for (int i = 0; i < primesList.length; i++) {
if (primesList[i] == true) {
numberOfPrimes++;
}
}
return numberOfPrimes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment