Best Time to Buy and Sell Stock I && II

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.

找到最大顺序差值

int maxProfit(int* prices, int pricesSize) {
    int min = 0;
    int max = 0;
    int result_max = 0;
    // go over array
    if(pricesSize == 0)
        return 0;
    min = max = prices[0];
    for(int i = 1; i < pricesSize; i++){
        
        // find the first min
        if(min > prices[i]){
            min = prices[i];
            max = prices[i];
        }
     // then find the first max
        if(max < prices[i]){
            max = prices[i];
        }
     // get the max result
        if(result_max < max - min)
            result_max = max - min;           
    }
    return result_max;
}

 

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

得到可以赚到的最大值

int maxProfit(int* prices, int pricesSize) {
    int min = 0;
    int max = 0;
    int sum = 0;
    if(pricesSize == 0)
        return 0;
    min = max = prices[0];
    // go over the array
    for(int i = 1; i < pricesSize; i++){
        // pass the prices less than front price
        if(min > prices[i]){
            min = prices[i];
            max = prices[i];
        }
        // if we will have owner sell it and buy it again
        if(max < prices[i]){
            max = prices[i];
            sum += max - min;
            min = prices[i];
        }
    }
    return sum;
}
  • 这里min和max的名字不太符合,追赶法更合适
  • 如果后面的值比前面的大就把差值加到sum上,然后重置min
posted @ 2015-12-26 11:17  dylqt  阅读(150)  评论(0编辑  收藏  举报