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

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

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值