Skip to content

Instantly share code, notes, and snippets.

@carlosmuvi carlosmuvi/maxProfit.java

Last active Jan 18, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.