leetcode:Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝网国际转运服务 编辑:程序博客网 时间:2024/06/07 20:04
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
解法1:
这种解法的思想主要是用到 最大连续子数组 先构建出辅助数组,xn-xn-1, xn-1 - xn-2, ..... x2-x1, x1-x0, 再求辅助数组的最大子数组和
int maxProfit(vector<int> &prices) { int size = prices.size(); if (size == 0 || size == 1) return 0; vector<int> aux(size-1); for (int i=1; i<size; i++) { aux[i-1] = prices[i]-prices[i-1]; } int max = 0; int curSum = 0; for (int i=0; i<size-1; i++) { if (curSum+aux[i] >= 0) { curSum += aux[i]; } else { curSum = 0; } if (curSum > max) max = curSum; } return max; }
class Solution {public: int maxProfit(vector<int> &prices) { int size = prices.size(); if (size == 0 || size == 1) return 0; vector<int> asendent(size); vector<int> desendent(size); desendent[0] = prices[0]; for (int i=1; i<size; i++) { if (prices[i] < desendent[i-1]) desendent[i] = prices[i]; else desendent[i] = desendent[i-1]; } asendent[size-1] = prices[size-1]; for (int j=size-2; j>=0; j--) { if (prices[j] > prices[j+1]) asendent[j] = prices[j]; else asendent[j] = prices[j+1]; } int max = 0; for (int i=0; i<size; i++) { if (asendent[i]-desendent[i] > max) max = asendent[i]-desendent[i]; } return max; }};
0 0
- 【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
- LeetCode Best Time to Buy and Sell Stock
- 实验四: 字符串和多维数组 实验
- suds文档
- 从头认识C—关于数组名
- 子龙山人
- hdu1026(bfs + priority_queue + 寻找路径)
- leetcode:Best Time to Buy and Sell Stock
- cocos2d-x3.2入门
- Binary Tree Level Order Traversal II (Java)
- 致腾讯的qq 6.5 会话窗口 合并 的产品经理
- 封装,多态,接口,集合,迭代器
- 2014.12.24学习笔记
- mmap使用方法介绍
- Listview中长按事件响应处理
- Java反射技术