class Solution {
public int bestTiming(int[] prices) {
int res = 0, minPrice = Integer.MAX_VALUE;
for(int i = 0; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
res = Math.max(res, prices[i] - minPrice);
}
return res;
}
}
class Solution {
public:
int bestTiming(vector& prices) {
//dp[i][0]_第i天没有股票的最大利润
int n = prices.size();
if(n0) return 0;
int dp[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
class Solution {
public int bestTiming(int[] prices) {
if(prices.length<=0){
return 0;
}
int max = 0;//股票最大收益
int min = prices[0];
for(int i=1;i<prices.length;i++){
min = min>prices[i]?prices[i]:min;
max = max<(prices[i]-min)?prices[i]-min:max;
}
return max;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
这个题最开始的时候是想要通过暴力法求解的,但是可能会有超时的问题,所以我们可以通过一次遍历,遍历的时候记录到目前为止最便宜的股票价格,如果后续遍历过程中某一天股票价格比min大,则可以计算max,max代表当前为止可以获得的最大的收益。
共以下 14 个回答
打卡
class Solution {
public int bestTiming(int[] prices) {
int n = prices.length;
if(n <= 1) return 0;
}
时间:O(n)
空间:O(1)
class Solution {& prices) {
public:
int bestTiming(vector
int minPrice = INT_MAX;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else {
maxProfit = max(maxProfit, price – minPrice);
}
}
return maxProfit;
}
};
打卡
时间复杂度$O(n)$,空间复杂度$O(1)$
时间复杂度:O(n)
空间复杂度:O(1)
时间复杂度O(n),空间复杂度O(1)
class Solution {
public int bestTiming(int[] prices) {
int cost = Integer.MAX_VALUE;
int profit = 0;
for(int price: prices){
cost = Math.min(price,cost);
profit = Math.max(price – cost, profit);
}
return profit;
}
//时间复杂度On
//空间复杂度O1
class Solution {& prices) {
public:
int bestTiming(vector
//dp[i][0]_第i天没有股票的最大利润
int n = prices.size();
if(n0) return 0;
int dp[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
};
时间复杂度:O(n)
空间复杂度:O(1)
时间复杂度O(N),空间复杂度O(1)
“`C++& prices) {
class Solution {
public:
int bestTiming(vector
if(prices.size() <= 1) { return 0; } int min = 99999; int profit = 0; for(int money : prices) { if(min > money)
{
min = money;
}
else
{
profit = max(money – min, profit);
}
}
};
“`
class Solution {& prices) {
public:
int bestTiming(vector
int profit = 0;
int cost = INT_MAX;
for(auto c : prices) {
cost = min(cost, c);
profit = max(profit, c – cost);
}
return profit;
}
};
//时间复杂度O(N)
//空间复杂度O(1)