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;
        }
    };
  • 相关阅读:
    django常用命令集合 待完善
    InSAR 数据
    InSAR 处理流程和原理
    InSAR 处理软件
    InSAR 参考书目,文献推荐
    InSAR
    小程序测试方案
    【非原创】测试环境的目的
    【非原创】测试的职责
    api自动生成思路
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3417029.html
Copyright © 2011-2022 走看看