LeetCode:123. Best Time to Buy and Sell Stock I

来源:互联网 发布:淘宝上购买 森海塞尔 编辑:程序博客网 时间:2024/06/02 09:55

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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
我的思路是这样:先把最小的值找出来,并用min记录其值,还用tempi记录其下标位置。如果tempi==numssize,那么证明其最小的值在最后,突然写着写着博客,发觉自己的思路已经错误了,因为不一定找出最小的值,只要找到一个值并后面的值小就行了。先把错误代码展示给大家看:

int maxProfit(int* prices, int pricesSize) {     int i,j;int tempi,tempj;int min=prices[0];int max;for(i=0;i<pricesSize;i++){if(prices[i]<min){min=prices[i];tempi=i;}}max=prices[tempi];if(tempi==i)return 0;else {for(j=tempi;j<pricesSize;j++){if(prices[j]>max){max=prices[j];tempj=j;}}return prices[tempj]-prices[tempi];}}

我也想到一个很暴力的算法,就是将每个结果都记录下来,找到最大值,如果最大值为负数,那么返回0,我觉得会有更加优化的算法:第i天卖出的最大收益即为第i天的股市价格减去[0,i-1]天内的最小股市价格,当第i天的股市价格比前面最低股市价格还低,则更新最低股市价格。然后取最大的股市收益,为DP问题。用profit[i]表示第i天的收益,则minBuyPrice = min(minBuyPrice, prices[i]),并且profit[i] = prices[i]-minBuyPrice. 然后取profit中的最大值。

AC:

class Solution {public:    int maxProfit(vector<int>& prices) {    int n = prices.size();        if(n == 0) return 0;        int maxPro = 0;        int minBuyPrice = prices[0];        for(int i = 1; i < n; i++){            minBuyPrice = min(minBuyPrice, prices[i]);             maxPro=max(maxPro,prices[i]- minBuyPrice);                    }        return maxPro;    }};




0 0
原创粉丝点击