leetcode-Best Time to Buy and Sell Stock II
2014-10-01 20:36
295 查看
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
这道题拖了好久啊。。犯了脑残错误一直没去调。。中间还去冲绳happy了一圈囧
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 i=0; int profit=0; int min=0; int max=0; int flag=false;
//如果股票价钱一直下跌就赚不到钱了,先check一下 while(i+1<prices.size()) { if(prices[i]<prices[i+1]){flag=true; break; } ++i; } if(!flag)return 0; i=0; while(i<prices.size()) { //findMin 找最低股票价钱买进 while((i+1)<prices.size()&&prices[i]>=prices[i+1])++i; if(i==prices.size())return profit; min=prices[i];
//findMax 找最高股票价钱的时候卖出 while((i+1)<prices.size()&&prices[i]<=prices[i+1])++i; max=prices[i]; profit+=(max-min); ++i; / } return profit; }
这道题拖了好久啊。。犯了脑残错误一直没去调。。中间还去冲绳happy了一圈囧
相关文章推荐
- 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 Solution
- leetcode 61: Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [Leetcode 51] 122 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 I II III
- [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 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)