zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell sock 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).

    分析:本题的意思就是说你同一时间只能拥有一只股票,在一段时间呢最低时买进,最高时卖出,赚得利润最多。相当于给你一组数组,例如{1,2,3,4,0,2,3,1},在刚开始1时买进,到4时,下一个数字为0了,4是这段时间的最高价,应卖出,然后再买进循环下去,把所得差额加起来就是最大利润了。

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

    python实现:

    class Solution:
        # @param prices, a list of integer
        # @return an integer
        def maxProfit(self, prices):
            nLen=len(prices)
            profit=0
            if nLen==0:
                return 0
            elif nLen<=1:
                return 0
            else:    
                for i in range(nLen-1):
                    diff=prices[i+1]-prices[i]
                    if diff>0:
                        profit+=diff
                return profit
  • 相关阅读:
    深入浅出Mybatis系列(一)---Mybatis入门
    深入浅出Mybatis系列(十)---SQL执行流程分析(源码篇)
    深入浅出Mybatis系列(九)---强大的动态SQL
    ZK请求处理
    ZK配置文件
    ZK数据同步
    集群间通信的消息类型
    ZK客户端
    Zookeeper崩溃恢复过程(Leader选举)
    Windows编程
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3574704.html
Copyright © 2011-2022 走看看