Best Time to Buy and Sell Stock
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.
题意:在数组中找两个数使得差的绝对值最大,但是保证第二个数大于等于第一个数。 难度EASY。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int minn;
for(int i=0; i < prices.size(); i++)
{
int x = prices[i];
if(i==0) {
minn = x;
continue;
}
if( x > minn) ans = max(ans, x - minn);
else minn = min(minn, x);
}
return ans;
}
};
本文介绍了一种寻找股票买卖最佳时机以实现最大利润的算法。该算法通过一次遍历找到数组中两个元素的最大差值,确保第二个元素的下标大于等于第一个元素的下标。适用于仅允许进行一次交易的情况。
750

被折叠的 条评论
为什么被折叠?



