您的位置:首页 > 其它

leetcode_122——Best Time to Buy and Sell Stock II(贪心算法)

2015-06-22 16:58 417 查看

Best Time to Buy and Sell Stock II

Total Accepted: 49554 Total Submissions: 129459My Submissions
Question Solution

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).

Hide Tags
Array Greedy

Have you met this question in a real interview?
Yes
这道题采用贪心算法的策略,要想整体最优,先要使得局部达到最优才行,这个就是先计算每个的局部最优

#include<iostream>
#include<vector>
using namespace std;

int maxProfit(vector<int>& prices) {
if(prices.empty())
return 0;
vector<int> vec=prices;
int len=vec.size();
if(len==1)
return 0;
vec[0]=0;
for(int i=1;i<len;i++)
vec[i]=prices[i]-prices[i-1];
int maxnum=0;
int k=0;
while(k<len)
{
int temp=0;
while(1)
{
if(k>=len||vec[k]<0)
break;
temp+=vec[k];
k++;
}
maxnum+=temp;
k++;
}
return maxnum;
}

int main()
{

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: