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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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 Explanation: In this case, no transaction is done, i.e. max profit = 0.
题目大意:就是输出一个在数组右边的数减去数组左边的数最大的差值。
做法也比较简单:申明两个数组,一个从左到右依次赋值目前为止最小的数,另一个从右到左依次赋值目前为止最大的数,然后两个数组每个位置对应的数进行相减,然后输出最大的值就是所求
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<int> min(n,0);
vector<int> max(n, 0);
int min1 = INT_MAX;
int max1 = INT_MIN;
for (int i = 0; i < n;i++)
{
if(min1<prices[i])
min[i] = min1;
else{
min[i] = prices[i];
min1 = min[i];
}
if(max1 > prices[n-1-i])
max[n - 1 - i] = max1;
else{
max[n - i - 1] = prices[n - 1 - i];
max1 = prices[n - 1 - i];
}
}
int max2 = 0;
for (int i = 0; i < n;i++)
{
if(max[i] - min[i] > max2)
max2 = max[i] - min[i];
}
return max2;
}
};