week14-leetcode #121-BestTimetoBuyandSellStock

来源:互联网 发布:windows ndk环境搭建 编辑:程序博客网 时间:2024/06/07 06:19

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 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

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)Input: [7, 6, 4, 3, 1]Output: 0In 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]表示到位置i为止的最大纪录,转移方程是:

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

max_profit[i]=max(max_profit[i1],prices[i]min_val[i])