(算法分析Week8)Best Time to Buy and Sell Stock[Easy]

来源:互联网 发布:苹果mac如何装虚拟机 编辑:程序博客网 时间:2024/06/14 19:44

121.Best Time to Buy and Sell Stock[Easy]

题目来源

Description

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.

给出一组数据,第i个数代表第i天石头的价格,选择在第i天买入在第j天(i < j)卖出,使得利润最大。

Solution

动态规划的问题。
两种思路:
(1)找到目前为止最小的那个数,然后找再它之后最大的那个数,求它们的差值即为最大利润值。

(2)考虑相邻两天石头的“差价”,目前的利润值+=price[i] - price[i-1],若利润值大于0,说明在第i天卖出比在i-1天更好;若小于0,说明第i天的石头价格比先前更低,当前利润值清零,继续往后比较,若能找到新的利润值比原来的最大利润值大,则替换数据。
*说的不是很清楚,对着代码举个例子就明白了

Complexity analysis

O(n)

Code

1)找最大差值,限制往后找。class Solution {public:    int maxProfit(vector<int>& prices) {        int maxPro = 0;        int minPrice = INT_MAX;        for(int i = 0; i < prices.size(); i++){            minPrice = min(minPrice, prices[i]);            maxPro = max(maxPro, prices[i] - minPrice);    }    return maxPro;    }};(2)动态规划class Solution {public:    int maxProfit(vector<int>& prices) {        int maxPro = 0;        int curPro = 0;        for (int i = 1; i < prices.size(); i++) {            curPro = max(0, curPro += prices[i] - prices[i-1]);            maxPro = max(curPro, maxPro);        }        return maxPro;    }};

Result

这里写图片描述

原创粉丝点击