zoukankan      html  css  js  c++  java
  • LeetCode

     

    Description

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

    Solution

    思路:只要列表中任意两个连续股价出现上涨趋势,就累积对应的增幅;对于股价下降的情况,则忽略之。

    python

     1 class Solution(object):
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         length = len(prices)
     8         if (length == 0 or length == 1):
     9             return 0
    10 
    11         cur_diff = 0
    12         sum_profit = 0
    13         for i in range(1, length):
    14             cur_diff = prices[i] - prices[i-1]
    15             if cur_diff > 0:
    16                 sum_profit = sum_profit + cur_diff
    17 
    18         return sum_profit

    cpp

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         int length = prices.size();
     5         if (length == 0 || length == 1)
     6             return 0;
     7 
     8         int sum_profit = 0;
     9         int cur_diff = 0;
    10         for (size_t i=1; i<length; ++i)
    11         {
    12             cur_diff = prices.at(i) - prices.at(i-1);
    13             if (cur_diff > 0)
    14             {
    15                 sum_profit += cur_diff;
    16             }
    17         }
    18 
    19         return sum_profit;
    20     }
    21 };
     
  • 相关阅读:
    Excel导入
    Git 操作命令
    java线程池
    jquery 初始化数据 添加html 第一次玩0.0
    设计模式六大原则之二:里氏替换原则
    升级指令
    strtok和strtok_r(转载)
    docker进阶之路-基础篇 | 二:portainer安装与基本使用
    docker进阶之路-基础篇 | 一:环境搭建
    集群式Quartz定时任务框架实践
  • 原文地址:https://www.cnblogs.com/gxcdream/p/7507457.html
Copyright © 2011-2022 走看看