zoukankan      html  css  js  c++  java
  • leetcode--Best Time to Buy and Sell Stock II

    1.题目描述:

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

    2.解法分析:

    有了上一篇文章的铺垫,这个问题很好解决,唯一需要注意的是题目中的一句话:However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again),before的含义很模糊,如果在一个时间点i卖出股票之后依然可以在时间点i买入股票,那么题目很简单,既然允许多次交易,直接求出查分数组里面所有正数的和即可。这个思路的代码是这样的:

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(prices.size() <= 1)return 0;
            vector<int>::iterator iter;
            
            int max=0;
            for(iter=prices.begin();iter!=prices.end()-1;++iter)
            {
                *iter = *(iter+1) - *iter;
                if(*iter>0)max+=*iter;
            }     
            return max;      
        }
    };
    提交结果之后运行正确,说明的确可以在第i天卖出之后继续买入:
    image
    ps : 实际上,如果第i天卖出之后不允许当天买入,这个问题也是有解的,只是稍微麻烦一些,代码如下:
     
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(prices.size() <= 1)return 0;
            vector<int>::iterator iter;
            for(iter=prices.begin();iter!=prices.end()-1;++iter)
            {
                *iter = *(iter+1) - *iter;
            }
            
            prices.pop_back();
            
            
            return maxDiffSum(prices,0);
            
            
            
        }
    private:
        int maxDiffSum(vector<int> &prices,int index)    
        {
            if(index >= prices.size())return 0;
            if(prices[index]<0)return maxDiffSum(prices,index+1);
            return max(maxDiffSum(prices,index+1),maxDiffSum(prices,index+2)+prices[index]);
        }
    };
  • 相关阅读:
    linux下svn命令使用大全(share)
    vi 编辑器命令 (share)
    如何成为一名优秀的前端工程师 (share)
    正则表达式入门教程&&经典Javascript正则表达式(share)
    动手学深度学习11- 多层感知机pytorch简洁实现
    动手学深度学习10- pytorch多层感知机从零实现
    动手学深度学习9-多层感知机pytorch
    动手学深度学习8-softmax分类pytorch简洁实现
    动手学深度学习7-从零开始完成softmax分类
    动手学深度学习6-认识Fashion_MNIST图像数据集
  • 原文地址:https://www.cnblogs.com/obama/p/3250043.html
Copyright © 2011-2022 走看看