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 };

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

  • 相关阅读:
    pymysql
    flask WTForms
    线程安全问题
    flask学习2
    @functools.wraps(func)
    Solidity开发神器Remix
    Web3j实现智能合约
    基于Ubuntu Docker环境下进行以太坊实践
    以太坊RLP机制分析
    以太坊网络服务分析
  • 原文地址:https://www.cnblogs.com/raichen/p/4932961.html
Copyright © 2011-2022 走看看