zoukankan      html  css  js  c++  java
  • [LeetCode] Best Time to Buy and Sell Stock

    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.

    解题思路:

    这个问题其实最长连续子序列和的变种。对于此题,设dp[i]为第i天卖出的最大收益,则dp[i] = max(0, dp[i - 1] + num[i] - num[i - 1])。故只需要顺序扫一遍即可。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int num = prices.size();
            int *dp = new int[num + 1];
            if(num <= 1) return 0;
            
            dp[0] = 0;
            int max_profit = 0;
            for(int i = 1;i < num;i++)
            {
                dp[i] = max(dp[i - 1] + prices[i] - prices[i - 1], 0);
                max_profit = max(max_profit, dp[i]);
            }
            return max_profit;
        }
    };
  • 相关阅读:
    10.28
    10.29
    11.05周四
    数据库增删改查
    11.03Tuesday
    11.10
    连接数据库
    10.30
    11.04周三
    10.27
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3417029.html
Copyright © 2011-2022 走看看