class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
// dp[i] is the max profit to sell the stock on day[i]
int max = 0;
int low = prices[0];
for(int i = 1; i < prices.size(); i++) {
low = std::min(low, prices[i]);
max = std::max(max, prices[i] - low);
}
return max;
}
};
class Solution {
public int maxProfit(int[] prices) {
int ans = 0, min = Integer.MAX_VALUE;
for (int price: prices) {
min = Math.min(min, price);
ans = Math.max(ans, price - min);
}
return ans;
}
}
public int maxProfit(int[] prices) {
int max = 0;
int min = Integer.MAX_VALUE;
for(int i = 0; i < prices.length; i++) {
if(prices[i] < min) {
min = prices[i];
} else {
max = Math.max(max, prices[i] - min);
}
}
return max;
}
class Solution {
public:
int maxProfit(vector& prices) {
int prev = 0, cur = 0;
int res = 0;
for(int i=1;i0)
cur = prev+prices[i]-prices[i-1];
else
cur = 0;
res=max(res, cur);
prev = cur;
}
return res;
}
};
以下是空间复杂度为O(n)的dp
class Solution {
public:
int maxProfit(vector& prices) {
vector dp(prices.size(), 0);
int res = 0;
for(int i=1;i
共以下 14 个回答
class Solution {
public int bestTiming(int[] prices) {
if(pricesnull||prices.length0){
return 0;
}
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i=1;i<prices.length;i++){
dp[i][1] = Math.max(dp[i-1][1],-prices[i]);
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
}
return dp[prices.length-1][0];
}
}
动态规划
“`java
class Solution {
public int bestTiming(int[] prices) {
//dp[i]表示第i天卖出的最大利润,则dp[i] = max(0, dp[i – 1] + prices[i] – prices[i – 1])
int length = prices.length;
if (length <= 1) { return 0; } if (length == 2) { return Math.max(0, prices[1] - prices[0]); } int[] dp = new int[length]; dp[0] = 0; int max = 0; for (int i = 1; i < length; i++) { dp[i] = Math.max(0, dp[i - 1] + prices[i] - prices[i - 1]); max = Math.max(dp[i], max); } return max; } }
时间复杂度:O(n)
空间复杂度:O(1)
#
MY动态规划
【思路】DP思路,在第i天卖掉股票的最大收益为prices[i]-minprice,后者为0…i天中股票最低价,因此需要一个min变量记录股票最低价
【复杂度】时间O(n),空间(1)
动态规划,找出该元素前的最小值即可
时间:O(n)
空间:O(1)
思路:动态规划,根据休息、买、卖三种状态进行转移
时间复杂度:O(n) 空间复杂度:O(n)
设置最小值买入价格,设置最大利润,一旦当前值大于买入就试着卖一下比较最大值
C++实现
“`C++& prices) {
int maxProfit(vector
int minPrice = prices[0];
int maxProfit = 0;
}
“`
c++实现& prices) {
int maxProfit(vector
int min_price = INT_MAX;
int max_profit = 0;
for(auto num:prices)
{
if(num<min_price)
{
min_price = num;
}
else
{
max_profit= max(max_profit,num-min_price);
}
}
return max_profit;
}
时间复杂度O(n),空间O(1)
以下是空间复杂度为O(n)的dp
怎么把我代码吞了?