LeetCode | Best Time to Buy and Sell Stock

来源:互联网 发布:江阴网络女主播被杀 编辑:程序博客网 时间:2024/05/25 05:37

I

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.

反应了一会才看懂题目的意思;
原来就是差不多类似股票,要求最低的时候买进然后最高的时候卖出,让我们找出最大的差价。
我们可以从头向后遍历,记录最小值最大值和最小最大值的位置。
最大值要求不低于最小值点的大小,最重要一点是:
最大值必须出现在最小值的后面
使用一个中间变量记录maxV-minV的大小

class Solution {public:    int maxProfit(vector<int>& prices) {        int n=prices.size();        int minV=INT_MAX,minPos=0,maxV=INT_MIN,maxPos=0;        int sum=INT_MIN;        for(int i=0;i<n;i++){            if(prices[i]<minV){                minV=min(minV,prices[i]);                minPos=i;                //如果小数出现在大数后面                if(maxPos<minPos) maxV=minV;            }            if(prices[i]>maxV){                maxV=max(maxV,prices[i]);                maxPos=i;            }            //最大的结果可能出现在中间过程中            sum=max(maxV>minV?maxV-minV:0,sum);        }        return sum>0?sum:0;        // vector<int> dp(n,1);        // for(int i=0;i<n;i++){        //     for(int j=0;j<i;j++){        //         if(dp[i]<dp[j]+1 && prices[j]<prices[i])        //         dp[i]=dp[j]+1;        //     }        // }        // printf("dp[n] %d\n",dp[n-1]);    }};

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

II具有一个很奇特的贪心性质,也即:
例如对于1,2,5,7
7-1=(2-1)+(5-2)+(7-5) 也就是说对于股价连续提升的区间,第一天买最后一天卖,和每天买卖,所得利润是一样的。

于是对于nums[i]>nums[i-1],即可立即卖出和买入。
检测到nums[i]

class Solution {public:    int maxProfit(vector<int>& prices) {        int n=prices.size();        if(n<=1) return 0;        int start=0,sum=0;        for(int i=1;i<n;i++){            if(prices[i]>prices[i-1])            sum+=prices[i]-prices[i-1];        }        // for(int i=0;i<n;i++){        //     //判断股票是下降趋势        //     if(i<n-1 && prices[i+1]-prices[i]<0){        //         sum+=prices[i]-prices[start];        //         start=i+1;        //     }        //     //最后一天,抛售股票        //     if(i==n-1) sum+= (prices[i]-prices[start])>0?(prices[i]-prices[start]):0;        // }        return sum;    }};
0 0
原创粉丝点击