121-簡單-買賣股票的最佳時機

蜜汁辣醬^_^發表於2020-10-29

在這裡插入圖片描述
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;
}

相關文章