您的位置:首页 > 其它

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

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了一圈囧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: