121. Best Time to Buy and Sell Stock

注意题目要求是只能交易一次:If you were only permitted to complete at most one transaction (

所以本质上寻找最大差价的前后股票,然后买入这次:
采用暴力搜索法,计prices[0]和prices[1, pricesSize-1]的最大差,然后从prices[1]计算prices[2,pricesSize-1]的最大差。

int maxProfit(int* prices, int pricesSize) {
    int max = 0;
    int i,j;
    int val;

    for(i = 0; i < pricesSize;i++)
        for(j = i+1; j < pricesSize; j++)
            if(prices[j] > prices[i]){
                val = prices[j] - prices[i];
                if(val > max)
                    max = val;
            }
    return max;
}

你可能感兴趣的:(121. Best Time to Buy and Sell Stock)