July 14, 2020

Algorithm to find maximum profit on buying and selling from an array




Class MaximumProfit{

private int maxProfit(int[] prices) {
int profit = 0;
int minimum = 0;
for (int current = 1; current < prices.length; current++) {
int previous = current - 1;
int next = current + 1;
if (prices[previous] > prices[current]) {
minimum = current;
}
if (prices[previous] <= prices[current] && (next == prices.length ||prices[current] > prices[next]  )) {
profit += (prices[current] - prices[minimum]);
}
}
return profit;
}

public static void main(String[] args) {
// int[] a = { 7, 1, 5, 3, 6, 4 };
int[] a = { 1, 2, 3, 4, 5 };
// int []a = {7,6,4,3,1};
// int[] a = { 1, 2, 3, 4, 1 };
System.out.println(new MaximumProfit().maxProfit(a));
}

}

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments