week14-leetcode #121-BestTimetoBuyandSellStock

week14-leetcode #121-BestTimetoBuyandSellStock

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

Question

Say you have an array for which the ith i t h element is the price of a given stock on day i 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

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)

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

Solution1 — 非DP

class Solution {
public:
  int maxProfit(vector<int>& prices) {
    int min_val = 999999;
    int max_diff = 0;
    for (int i = 0; i < prices.size(); i++) {
      min_val = (min_val > prices[i]) ? prices[i]: min_val;
      max_diff = (max_diff < prices[i]-min_val) ? (prices[i]-min_val) : max_diff;
    }
    return max_diff;
  }
};

思路:遍历一次prices数组,到位置i的时候记录下当前时刻的最小值是多少,求出当前为止最大的利润。

Solution2 — DP

class Solution {
public:
  int maxProfit(vector<int>& prices) {
    int size = prices.size();
    int *max_profit = new int[size];
    int *min_val = new int[size];
    min_val[0] = prices[0];
    max_profit[0] = 0;
    for (int i = 1; i < size; i++) {
      min_val[i] = min(min_val[i-1], prices[i]);
      max_profit[i] = max(max_profit[i-1], prices[i]-min_val[i]);
    }
    return max_profit[size-1];
  }
};

思路:
max_profit[i] m a x _ p r o f i t [ i ] 表示到位置 i i 为止的最大利润,转移方程是:

初始化max_profit[0]=0,min_val[0]=prices[0]

max_profit[i]=max(max_profit[i1],prices[i]min_val[i]) m a x _ p r o f i t [ i ] = m a x ( m a x _ p r o f i t [ i − 1 ] , p r i c e s [ i ] − m i n _ v a l [ i ] )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值