2016年2月1日 星期一

LEET code -- Best Time to Buy and Sell Stock II

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).

跟第一版不同
這次可以重複購買,但是只能先買在賣

這可以把買賣換成訊號來看
這個問題可以看成找相對高峰

於是改第一版的就可以


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int maxProfit(int* prices, int pricesSize) {
    if(prices==NULL || pricesSize <2)return 0;
    int size=pricesSize;
    int max=0,buydate=0,selldate=1,buy=prices[0],sell=prices[1];
    int income=0;
    for(int i =1;i<size;i++){
        if(prices[i] > sell){
            sell = prices[i];
            selldate=i;
        }else if(prices[i] < sell){
            income+=max;
            max=0;
            buy = prices[i];
            buydate = i;
            sell = prices[i];
            selldate=i;
        }
        if(prices[i]< buy){
            buy = prices[i];
            buydate = i;
            sell = prices[i];
            selldate=i;
            //income+=max;
            //max=0;
        }
        if ( selldate > buydate){
            max = (max>(sell-buy))? max:(sell-buy);
        }
    }
    income+=max;
    return income; 
}

沒有留言:

張貼留言