<LeetCode OJ> 122. Best Time to Buy and Sell Stock II
2016-01-15 22:02
489 查看
122. Best Time to Buy and Sell Stock II
My SubmissionsQuestion
Total Accepted: 73349 Total
Submissions: 179674 Difficulty: Medium
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).
同一时间不能做多次交易(买一次再卖一次,或者卖一次再买一次算一次交易),意思就是说在你买股票之前你必须卖掉股票
(即你手头最多允许保留一只股票,同时隐含了每次只能交易一次的意思)
Subscribe to see which companies asked this question
Hide Tags
Array Greedy
Show Similar Problems
分析:
题目理解错误,刚开始没有任何思路....这题通过率40%,我的内心是崩溃的!!!
题目:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。设计一个算法找出最大利润
但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。
分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格(即为了最大利润,只要有利润存在就利用交易次数的无限制贪心的获取),就累加到收益中。
代码:时间O(n),空间O(1)。
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() < 2) return 0; int profit = 0; for(auto ite = prices.begin()+1; ite != prices.end(); ite++) profit += max(*ite - *(ite-1),0); return profit; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50526099
原作者博客:http://blog.csdn.net/ebowtang
相关文章推荐
- 初探C++流
- 彩票问题 不输出相同的数字
- C/C++小知识
- 1035
- Educational Codeforces Round 5 A. Comparing Two Long Integers
- Educational Codeforces Round 5 B. Dinner with Emma B. Dinner with Emma
- Educational Codeforces Round 5 C. The Labyrinth
- Educational Codeforces Round 5 D. Longest k-Good Segment
- 在知乎上给评论加入跳转链接--XSS练手
- MacBook外接显示器设置方法(新手入门贴)
- java加密、解密技术系列:Base64
- 网易新闻
- 针对之前的Canvas的一个小小的改版,算作canvas(二)吧
- 蓝懿IOS阶段测试
- 插入排序的一种尾递归实现-C
- UI_1
- python学习第十课续 :线程池
- linux变量篇(三) 命令行参数变量传递
- 怎样学习java?
- 开发中常见问题