• [LeetCode]31. 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.

    解法:限制最多允许交易一次。假设第i天交易后所获最大收益为maxv,则要使maxv最大,则要么maxv为前i-1天交易后所获得的最大收益,要么就是第i天股票价格(卖出价格)减去前i-1天的最低价格(买入价格)所获的收益。使用动态规划求解。时间复杂度O(n),空间复杂度O(1)。

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            if (n < 2) return 0;
            int curMin = prices[0], maxVal = 0;
            for (int i = 1; i < n; i++) {
                curMin = min(curMin, prices[i]);
                maxVal = max(maxVal, prices[i] - curMin);
            }
            return maxVal;
        }
    };
  • 相关阅读:
    2020软件工程第三次作业
    2020软件工程第二次作业
    2020软件工程第一次作业
    线性回归算法
    K均值算法--应用
    K均值算法
    机器学习相关数学基础
    机器学习概述
    语法制导的语义翻译
    作业十四----算符优先分析
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4888184.html
Copyright © 2020-2023  润新知