zoukankan      html  css  js  c++  java
  • 风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<

    // ConsoleApplication10.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Solution {
    public:
    	/**
    	* 计算你能获得的最大收益
    	*
    	* @param prices Prices[i]即第i天的股价
    	* @return 整型
    	*/
    	int calculateMax(vector<int> prices) {
    	
    		vector<int> vec1, vec2;
    		int earn = 0, max = earn;;
    		for (int i = 0;i < prices.size() ;i++)
    		{
    			vec1.push_back(prices[i]);
    			vec2.clear();
    			for (int j = i+1;j < prices.size();j++)
    			{
    				vec2.push_back(prices[j]);
    			}
    			earn = calculateEarn(vec1) + calculateEarn(vec2);
    			if (earn > max)
    			{
    				max = earn;
    			}
    		}
    		return max;
    	}
    	int calculateEarn(vector<int> prices) {
    		//没有一笔交易
    		int  earn = 0;
    		//交易一次
    		int max = earn;
    		for (int i = 0;i < prices.size();++i)
    		{
    			//第i天买入
    			int out = prices[i];
    
    			for (int j = i;j < prices.size();++j)
    			{
    				//第j填卖出
    				int in = prices[j];
    				earn = in - out;
    				if (earn > max)
    				{
    					max = earn;
    				}
    			}
    		}
    		return max;
    	}
    };
    
    int main()
    {
    	Solution so;
    	//vector<int> prices = { 3,8,5,1,7,8 };
    	
    	vector<int> prices = { 10, 7, 3, 1 };
    	cout << "收益:" << so.calculateMax(prices)<<endl;
    	cout << "收益:" << so.calculateEarn(prices) << endl;;
    	cout << endl;
    	return 0;
    }
    

    //先计算交易一次的
    //然后计算交易两次的

  • 相关阅读:
    visual studio disable git
    app常见性能测试点
    App测试流程及测试点(个人整理版)
    APP测试要点
    APP端测试常见的功能点
    一文搞懂性能测试常见指标
    为什么会有生产bug?
    线上出了bug,是谁的责任?
    生产上线发现重大Bug的思考
    项目上线后出现Bug,该如何处理?
  • 原文地址:https://www.cnblogs.com/wdan2016/p/6413659.html
Copyright © 2011-2022 走看看