leetcode:Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝网国际转运服务 编辑:程序博客网 时间:2024/06/07 20:04

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.


解法1: 

这种解法的思想主要是用到  最大连续子数组     先构建出辅助数组,xn-xn-1,  xn-1 - xn-2, ..... x2-x1, x1-x0,    再求辅助数组的最大子数组和

    int maxProfit(vector<int> &prices) {                int size = prices.size();                if (size == 0 || size == 1)            return 0;                vector<int> aux(size-1);                for (int i=1; i<size; i++)        {            aux[i-1] = prices[i]-prices[i-1];        }                int max = 0;        int curSum = 0;        for (int i=0; i<size-1; i++)        {            if (curSum+aux[i] >= 0)            {                curSum += aux[i];            }            else            {                curSum = 0;            }                        if (curSum > max)                max = curSum;        }                return max;    }


解法2:

class Solution {public:    int maxProfit(vector<int> &prices) {                int size = prices.size();                if (size == 0 || size == 1)            return 0;                vector<int> asendent(size);        vector<int> desendent(size);                desendent[0] = prices[0];        for (int i=1; i<size; i++)        {            if (prices[i] < desendent[i-1])                desendent[i] = prices[i];            else                desendent[i] = desendent[i-1];        }                asendent[size-1] = prices[size-1];        for (int j=size-2; j>=0; j--)        {            if (prices[j] > prices[j+1])                asendent[j] = prices[j];            else                asendent[j] = prices[j+1];        }                int max = 0;        for (int i=0; i<size; i++)        {            if (asendent[i]-desendent[i] > max)                max = asendent[i]-desendent[i];        }                return max;    }};



0 0
原创粉丝点击