zoukankan      html  css  js  c++  java
  • 【LeetCode】122. Best Time to Buy and Sell Stock II

    题目:

    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).

    提示:

    此题应使用贪心算法的思想。我所采用的贪心规则如下:

    • 从第一个元素开始遍历至最后一个元素;
    • 若下一个元素比当前元素大,那么就抛售;并以下一个元素的价钱买入,同时累加利润;
    • 若下一个元素比当前元素小,那么就以下一个元素的价钱买入(若连续出现递减的情况,那么最后的买入价格是最后那个最小的元素);

    代码:

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.size() == 0) return 0;
            int buy_in = prices[0], sum = 0;
            for (int i = 1; i < prices.size(); ++i) {
                if (prices[i] > buy_in) {
                    sum += prices[i] - buy_in;
                    buy_in = prices[i];
                } else {
                    buy_in = prices[i];
                }
            }
            return sum;
        }
    };

    后来在论坛上发现了更加简洁的解法,核心思想其实是比较类似的:

    int maxProfit(vector<int> &prices) {
        int ret = 0;
        for (size_t p = 1; p < prices.size(); ++p) 
          ret += max(prices[p] - prices[p - 1], 0);    
        return ret;
    }

    其实就是只要有涨就先卖再买,但是这种解法更加简洁清楚。

  • 相关阅读:
    Centos系统安装
    HPDL380G8平台11.2.0.3 RAC实施手册
    bash的位置变量和特殊变量
    bash中的算术运算
    bash文本查看及处理工具
    bash快捷键及输入输出重定向
    bash文件名统配
    文本搜索grep知识点总结
    sed练习
    流编辑器sed知识点总结
  • 原文地址:https://www.cnblogs.com/jdneo/p/4738842.html
Copyright © 2011-2022 走看看