Leetcode Best Time to Buy and Sell Stock 2
来源:互联网 发布:呼死你在淘宝上叫什么 编辑:程序博客网 时间:2024/06/01 07:45
/************************************************************************
*
* 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 <iostream>#include <vector>using namespace std;int maxProfit(vector<int> &price){ int begin = 0, end = 0, max = 0; //这里添加了两个标志,判断股票状态 bool up = false, down = false; for (int i = 1; i<price.size(); i++) { if (price[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<int>price = { 23,24,27,18,23,19,31 }; cout << maxProfit(price) << endl;}
0 0
- Leetcode Best Time to Buy and Sell Stock 2
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- 重温6 ListView相关|单位dp/sp
- 为什么在C++中需要虚函数
- n*log(3)n排序算法 初稿
- android-----XUtils框架之BitmapUtils加载照片实现
- 前端——浮动清除
- Leetcode Best Time to Buy and Sell Stock 2
- tcp状态
- Javascript模块化编程(一):模块的写法
- 检查字符串是否存在字符变位
- PHP打印输出数组内容及结构函数print_r与var_dump
- 32岁,重回研发,不为别的,给自己过去一个交待!
- Access denied for user 'root '@'连接的ip'(using password:YES)
- 安装完Hadoop之后,命令行输入hadoop却找不到命令的解决方法
- WCF实现http访问地址后面带参数访问方式