1暴力求解
int maxProfit(int* prices, int pricesSize) {
int temp1 = 0;
int temp2 = 0;
for (int i = 0; i < pricesSize - 1; i++) {
for (int j = i+1; j < pricesSize; j++) {
if (prices[j] <= prices[i]){
continue;
}
temp2 = prices[j] - prices[i];
if (temp1 < temp2){
temp1 = temp2;
}
}
}
return temp1;
}
2动态规划
int maxProfit(int* prices, int pricesSize) {
int profit = 0;
int minprices = 0;
int temp;
if ((prices == NULL) || (pricesSize <=0 )) {
return 0;
}
minprices = prices[0];
for (int i = 0; i < pricesSize; i++) {
if (prices[i] < minprices) {
minprices = prices[i];
continue;
}
temp = prices[i] - minprices;
if (profit < temp) {
profit = temp;
}
}
return profit;
}