// 寻找 max(prices[j] - prices[i]) [j > i]
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) return 0;
int min = prices[0];
int ans = 0;
for (int num : prices) {
ans = Math.max(ans, num - min);
min = Math.min(min, num);
}
return ans;
}
}
class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0)
return 0;
int p = 0;
int m = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < prices[i - 1])
m = prices[i];
else {
if (prices[i] - m > p)
p = prices[i] - m;
prices[i] = m;
}
}
return p;
}
//优化
public int maxProfit2(int[] prices) {
int min = Integer.MAX_VALUE;
int p = 0;
for(int i = 0; i < prices.length; i++){
if(prices[i] < min){
min = prices[i];
}else{
p = Math.max(p, prices[i] - min);
}
}
return p;
}
}
class Solution {
public int maxProfit(int[] prices) {
//dp动态规划
//1、5步走;
//1. 确定dp数组以及下标的含义;2、递推公式 3、初始化、4、遍历顺序
if (prices.length == 0){
return 0;
}
int [] dp = new int[prices.length];
dp[0] = 0;
int min = prices[0];
for (int i = 1;i<prices.length;i++){
min = Math.min(prices[i],min);
dp[i] = Math.max(dp[i-1],prices[i]-min);
}
return dp[prices.length-1];
}
}
var maxProfit = function(prices) {
let min = Infinity;
let max = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
}
max = Math.max(prices[i] - min, max)
}
return max;
};
class Solution {
public int maxProfit(int[] prices) {
int m = prices.length;
int x = Integer.MAX_VALUE;
int dp = 0;
for(int i = 0;i < m;i++){
x = Math.min(x,prices[i]);
if(prices[i] - x > 0){
dp = Math.max(prices[i] - x,dp);
}
}
return dp;
}
}
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int max = 0;
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;
}
}
共以下 15 个回答
计算过程中直接记录当前出现过的最大最小值也可以,这时对于数组的遍历需要从0开始
迭代
时间复杂度:O(N)
空间复杂度:O(1)
时间O(n)
空间O(1)
C++
很简单的一道dp& prices) { dp(len+1);
class Solution {
public:
int maxProfit(vector
int len = prices.size();
vector
dp[0] = 0;
if(len <= 1) return 0;
int minn = prices[0];
for(int i = 1; i < prices.size(); ++i) {
dp[i] = max(prices[i] – minn, dp[i-1]);
if(minn > prices[i]) minn = prices[i];
}
return dp[len-1];
}
};
时间复杂度O(n),空间复杂度为O(1)
时间:O(n),空间:O(1)
均是O(N)