LeetCode: Best Time to Buy and Sell Stock II
来源:互联网 发布:关键词快速排名软件 编辑:程序博客网 时间:2024/05/22 04:36
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).
class Solution {public: int maxProfit(vector<int> &prices) { int min = INT_MAX, profit = 0, total = 0;; int size = prices.size(); for(int i = 0; i < size; i++) { if(prices[i] < min){ min = prices[i]; } if(prices[i] - min > profit){ profit = prices[i] - min; } if(i == size - 1 || prices[i+1] < prices[i]) { total += profit; profit = 0; min = INT_MAX; } } return total; }};
Round 2:
class Solution {public: int maxProfit(vector<int> &prices) { int min = INT_MAX; int preMax = 0; int result = 0; for(int i = 0; i < prices.size(); i++) { if(prices[i] < min) min = prices[i]; if(prices[i] - min > preMax) preMax = prices[i]-min; else { if(preMax != 0) { result += preMax; min = INT_MAX; preMax = 0; i--; } } } result += preMax; return result; }};
0 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- LeetCode-Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- Html(5)CSS样式入门
- 析构(Destructor)内存垃圾回收机制
- 【Android】 Canvas、Path 和 Paint 实例 (游戏开发必备)
- 周末小测——B(poj2458 Prim)
- dark corners of C++
- LeetCode: Best Time to Buy and Sell Stock II
- 面试大总结之一:Java搞定面试中的链表题目
- 周末小测——C(ZOJ 1061)
- NSURL Class Reference (部分)
- DUILIB效率提升
- 说一下Docker(一)
- 百度直达号,一场自high的喜剧
- 市场低迷怎么才能做好自己的企业
- 年度回忆录-2014(上半年)