121.LeetCode Best Time to Buy and Sell Stock(easy)[数组 动态规划]

来源:互联网 发布:淘宝联盟站长 编辑:程序博客网 时间:2024/05/28 23:20

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.

这个题是要通过解决购买一次进股票,然后选择某天销售取得最大利润的问题。这里利用dp数据存放到目前为止价格最小的股票价格,然后通过profit保存当前为止的最大的利润。

class Solution {public:    int maxProfit(vector<int>& prices) {        int n = prices.size();        if(n<=1) return 0;        int dp[n];//存放到目前为止最小的元素        dp[0] = prices[0];        int profit = 0;        for(int i=1;i<n;i++)        {            if(prices[i]<dp[i-1])            {                dp[i] = prices[i];            }else{                dp[i] = dp[i-1];                int temp = prices[i]- dp[i-1];                if(temp>profit)                   profit = temp;            }              }        return profit;    }};


0 0
原创粉丝点击