zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    解题思路:

    遇到price[i] < price[i-1] ,则将前一段时间的收益加上。注意处理末尾元素。

    代码:

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if (prices.size() == 0) {
                return 0;
            }
            int lower = 0, higher = 0;
            int ans = 0;
    
            for (int i = 1; i < prices.size(); i++){
                if (prices[i] >= prices[higher]){
                    higher++;
                }
                else {
                    ans += (prices[higher] - prices[lower]);
                    lower = i;
                    higher = i;
                }
            }
            if (prices[prices.size()-1] > prices[lower]) {
                ans += (prices[prices.size() - 1] - prices[lower]);
            }
            return ans;
    
        }
    };
  • 相关阅读:
    子网掩码的作用与IP网段的划分
    DHCP服务器
    Anaconda安装、更新第三方包
    time模块的使用
    TensorFlow安装
    机器学习-线性回归
    机器学习
    Pyhton-类(2)
    python-类(1)
    Python-函数
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3727819.html
Copyright © 2011-2022 走看看