博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode Best Time to Buy and Sell Stock 2
阅读量:4185 次
发布时间:2019-05-26

本文共 1543 字,大约阅读时间需要 5 分钟。

/************************************************************************

*
* 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).
*
**********************************************************************/
题目解析:例如股票的变化如下
23,24,27,18,23,19,31
这里我们可以随意操作股票,因此,只要将股票下降的前一天,立即收回股票,
明天继续入手。
因此可分在第一天入手,第三天出手
第四天入手,第五天出手
第六天入手,第七天出手

// Author : yqtao// Date   : 2016-6.19// Email  :yqtao@whu.edu.cn#include "stdafx.h"#include 
#include
using namespace std;int maxProfit(vector
&price){ int begin = 0, end = 0, max = 0; //这里添加了两个标志,判断股票状态 bool up = false, down = false; for (int i = 1; i
price[i - 1] && up == false) { // goes up begin = i - 1; up = true; down = false; } if (price[i] < price[i - 1] && down == false) { // goes down end = i - 1; down = true; up = false; max += (price[end] - price[begin]); } } // 考虑边界条件 if (begin < price.size() && up == true) { end = price.size() - 1; max += (price[end] - price[begin]); } return max;}int main(){ vector
price = { 23,24,27,18,23,19,31 }; cout << maxProfit(price) << endl;}

转载地址:http://vsdoi.baihongyu.com/

你可能感兴趣的文章
JAVA编写HTTP代码并发布在网上
查看>>
JDBC连接数据库的原理和步骤
查看>>
开发微信公众平台的基本功能
查看>>
JSP内置对象的学习
查看>>
用java写文件输入输出流,实现复制粘贴的方法
查看>>
学习JSP的方法步骤(参考)
查看>>
JSP中常见TOMCAT错误代码原因
查看>>
MyEclipse中WEB项目加载mysql驱动方法
查看>>
常见编写JAVA报错总结
查看>>
org.gjt.mm.mysql.Driver和com.mysql.jdbc.Driver的区别
查看>>
UTF-8和GBK有什么区别
查看>>
增加MyEclipse分配内存的方法
查看>>
头痛与早餐
查看>>
[转]在ASP.NET 2.0中操作数据::创建一个数据访问层
查看>>
Linux命令之chmod详解
查看>>
【java小程序实战】小程序注销功能实现
查看>>
leetcode Unique Paths II
查看>>
几个大数据的问题
查看>>
CareerCup Pots of gold game:看谁拿的钱多
查看>>
CarreerCup Sort Height
查看>>