Leetcode-Best Time to Buy and Sell Stock

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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

暴力解法很容易:

int maxProfit(int* prices, int pricesSize) {
    int prof = 0,cur = 0;
    for(int i=0;i<pricesSize;i++)
    {
        for(int j=i+1;j<pricesSize;j++)
        {
            cur = prices[j]-prices[i];
            prof = (cur>prof)?cur:prof;
        }
    }
    return (prof>0)?prof:0;
}

看了排名第一的解法,将这个题目与求最大连续子序列和的问题联系起来,很cool。
附上Kadane’s algorithm

def max_subarray(A):
max_ending_here = max_so_far = A[0]
for x in A[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far

题目的目的就是求解 prices[a] - prices[b]的最大值,并且要a>=b;可以转换为prices[a] - prices[c] + prices[c] - prices[b]….的最大值.

#define MAX(A,B) ((A)>(B))?(A):(B)
int maxProfit(int* prices, int pricesSize) {
    int maxProf = 0,curProf = 0;
    for(int i=1;i<pricesSize;i++)
    {
        curProf = MAX(curProf+prices[i]-prices[i-1],prices[i]-prices[i-1]);
        maxProf = MAX(maxProf,curProf);
    }
    return maxProf;
}

很酷炫的O(N)解法!

发布了24 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ck1n9/article/details/78329218