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.
#include<stdio.h>
int maxProfit(int *prices, int n) {
int i = 0;
int profit = 0, min = prices[0];
if(n == 0) return 0;
for(i = 1; i < n; i++){
if(prices[i] - min > profit) profit = prices[i] - min;
if(prices[i] < min) min = prices[i];
}
return profit;
}
void main() {
int prices[] = {7,6,5,4,3,2,1,0};
int n = 8;
printf("%d\n", maxProfit(prices, n));
}