LintCode_149_买卖股票的最佳时机
来源:互联网 发布:网络映射地址 编辑:程序博客网 时间:2024/04/27 21:22
问题描述
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例
给出一个数组样例 [3,2,3,1,2], 返回 1
求解
此问题是“最大子数组”问题的一个应用。
class Solution {public: /* * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> prices) { // write your code here if (prices.size() < 2) return 0; int max = 0; int sum = 0; auto begin = prices.cbegin() + 1; auto end = prices.cend(); for (auto it = begin; it != end; ++it) { int diff = *it - *(it - 1); //if (it == begin) max = diff; //如果考虑增量全为负数的情况,这一行不加注释 sum += diff; if (max < sum) max = sum; if (sum < 0) sum = 0; } return max; }};
阅读全文
0 0
- LintCode_149_买卖股票的最佳时机
- LintCode_149_买卖股票的最佳时机
- 买卖股票的最佳时机
- 买卖股票的最佳时机
- 买卖股票的最佳时机
- LintCode-买卖股票的最佳时机
- 题目:买卖股票的最佳时机
- LintCode--买卖股票的最佳时机
- Lintcode:买卖股票的最佳时机
- 买卖股票的最佳时机 II
- 买卖股票的最佳时机 III
- 买卖股票的最佳时机|_1
- 买卖股票的最佳时机||_1
- 买卖股票的最佳时机,lintcode
- 【LintCode】买卖股票的最佳时机
- lintcode--买卖股票的最佳时机
- Lintcode 买卖股票的最佳时机
- 买卖股票的最佳时机-LintCode
- 双倍回文(BZOJ-2342)(manacher+并查集)
- Kaldi WFST 构图 学习
- 国际化饥和屏幕适配 沉浸式
- 使用jsoup,爬取省/市/区/县/镇/乡 地域划分消息
- HDU 6170 字符串Dp
- LintCode_149_买卖股票的最佳时机
- XListView上拉加载下拉刷新
- springmvc参数绑定
- larave框架安装
- HTML5 canvas画圆
- 集训第二十四天(2017/8/23):二维树状数组&三维树状数组
- C/C++,用0x3f3f3f3f表示无穷大,0xc0c0c0c0表示无穷小
- (reading)Deep Visual-Semantic Alignments for Generating Image Descriptions
- java防止页面脚本注入 特殊字符过滤器