121. Best Time to Buy and Sell Stock
public class Solution {
public int maxProfit(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
}
执行用时 :1 ms, 在所有 java 提交中击败了99.98%的用户
内存消耗 :37.1 MB, 在所有 java 提交中击败了85.05%的用户
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int min=prices[0];
int profit=0;
for(int i =1;i<prices.length;i++){
min = Math.min(min,prices[i-1]);
profit = Math.max(profit,prices[i]-min);
}
return profit;
}
}
执行用时 :2 ms, 在所有 java 提交中击败了83.04%的用户
内存消耗 :36 MB, 在所有 java 提交中击败了98.13%的用户
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int min = prices[0];
int profit = 0;
for (int i = 1; i < prices.length; i++) {
profit = Math.max(prices[i] - min, profit);
min = Math.min(min, prices[i]);
}
return profit;
}
执行用时 :48 ms, 在所有 python 提交中击败了97.55%的用户
内存消耗 :12.7 MB, 在所有 python 提交中击败了20.10%的用户
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0) return 0;
int p = 0;
int m = prices[prices.size()-1];
// cout<<"Here";
for (int i = prices.size()-1; i >=0; i--) {
m = max(m,prices[i]);
p = max(p,m - prices[i]);
}
return p;
}
};
执行用时 :4 ms, 在所有 cpp 提交中击败了98.57%的用户
内存消耗 :9.4 MB, 在所有 cpp 提交中击败了70.72%的用户
评论区