zoukankan      html  css  js  c++  java
  • 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).

    解析:

    贪心法,低进高出,把所有正的价格差价相加起来。
    把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 数组长度

     1 class Solution
     2 {
     3 public:
     4     int maxProfit(vector<int> &prices)
     5     {
     6         int sum = 0;
     7         for (int i = 1; i < prices.size(); i++)
     8         {
     9             int diff = prices[i] - prices[i - 1];
    10             if (diff > 0) sum += diff;
    11         }
    12         return sum;
    13     }
    14 };

    这题相处了低进高出了,但是想麻烦的,总想着先求出出拐点,再计算拐点之间的差

  • 相关阅读:
    HASH算法介绍
    windowsOracle19C安装
    Oracle快照控制文件理解
    Swap空间扩展
    OracleDBA职责—备份与恢复技术—RMAN4
    OI回忆录
    HEOI2020(NEW)
    HEOI2020
    省选前奇怪的心情减少了
    $Mom$
  • 原文地址:https://www.cnblogs.com/raichen/p/4932961.html
Copyright © 2011-2022 走看看