121. Best Time to Buy and Sell Stock

来源:互联网 发布:好听的音乐剧歌曲知乎 编辑:程序博客网 时间:2024/06/06 15:38

一、问题:

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.

二、解题

(1)暴力解法:

class Solution {public:    /*     暴力解法两次循环,找出最大差     超时。    */    int maxProfit(vector<int>& prices)     {        int max = 0;        int n = prices.size();        for (int i = 0; i < n-1; i++)        {            for (int j = i + 1; j < n; j++)            {                if (prices[j] - prices[i] > max)                {                    max = prices[j] - prices[i];                }            }        }        return max;    }};
class Solution {public:    /*    卖出价格从右边遍历,买进从左边遍历。    复杂度1/2*O(n^2)    */    int maxProfit(vector<int>& prices)    {        int max = 0;        int n = prices.size();        int i = 0;        while (n - 1 > i)        {            for (int i = 0; i < n - 1; i++)            {                if (prices[n - 1] - prices[i] > max)                {                    max = prices[n - 1] - prices[i];                }            }            n--;        }        return max;    }};
原创粉丝点击