# leetcode 121. Best Time to Buy and Sell Stock

165人阅读 评论(0)

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)


Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.


class Solution {
public:
static bool sortbyprice(pair<int,int>&obj1,pair<int,int>&obj2){
if(obj1.first>obj2.first){
return false;
}
return true;
}
int maxProfit(vector<int>& prices)
{
int days = prices.size();
if (days <= 1)return 0;
int start = 0, end = 1;
int profit = 0;
while (end<days)

if (prices[end]>prices[start])
profit = max(profit, prices[end] - prices[start]);
else
start = end;
end++;
}
return profit;
}
/*
int maxProfit(vector<int>& prices) {
int max_profite = 0;
int i,j;
int n = prices.size();
bool flag=false;
vector<pair<int,int>>pricesort;
for(i=0;i<n;i++){
pricesort.push_back(make_pair(prices.at(i),i));
}
sort(pricesort.begin(),pricesort.end(),sortbyprice);
for (j=n-1;j>=1;j--){
if((pricesort.at(j).second>pricesort.at(j-1).second)&&(pricesort.at(j).first>pricesort.at(j-1).first)){
flag = true;
}
}
if(flag==false){
return 0;
}
for(i=0;i<n-1;i++){
for(j=n-1;j!=i;j--){
if(pricesort.at(j).second>pricesort.at(i).second){
return pricesort.at(j).first-pricesort.at(i).first;
}
}
}
return 0;
}*/
};
/*
class Solution {
public:
int maxProfit(vector<int>& prices) {
int max_profite = 0;
int i,j;
int n = prices.size();
for(i=0;i<n-1;i++){
for(j=i+1;j<n;j++){
max_profite = max_profite>prices.at(j)-prices.at(i)?max_profite:prices.at(j)-prices.at(i);
}
}
return max_profite;
}
};*/

0
0

个人资料
• 访问：133542次
• 积分：1802
• 等级：
• 排名：千里之外
• 原创：17篇
• 转载：184篇
• 译文：0篇
• 评论：15条
最新评论