今天发现leetcode比别的都好。。。因为面试面到121题,我愚笨的脑袋用了两个for循环,只用一个for循环我是想不出的。
121:
class Solution {
public:
int maxProfit(vector<int>& prices) {
size_t size = prices.size();
if(size <= 1) return 0;
int min = INT_MAX, max = INT_MIN;
for(int i=0; i<size; i++) {
if(min > prices[i]) min = prices[i];
if(max < prices[i] - min) max = prices[i] - min;
}
return max;
}
};
122:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if(size <= 1) return 0;
int max = 0;
for(int i=1; i<size; i++) {
max += prices[i] > prices[i-1] ? prices[i] - prices[i-1] : 0;
}
return max;
}
};
123:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if(size <= 1) return 0;
int *ascandMax = new int[size]();
int minPrice = prices[0];
int maxProf = 0;
for(int i=0; i<size; i++) {
maxProf = max(maxProf, prices[i]-minPrice);
minPrice = min(minPrice, prices[i]);
ascandMax[i] = maxProf;
}
int *descandMax = new int[size]();
int maxPrice = prices[size-1];
maxProf = 0;
for(int i=size-2; i>=0; i--) {
maxProf = max(maxProf, maxPrice-prices[i]);
maxPrice = max(maxPrice, prices[i]);
descandMax[i] = maxProf;
}
maxProf = 0;
for(int i=0; i<size; i++) {
maxProf = max(maxProf, ascandMax[i] + descandMax[i]);
}
delete[] ascandMax;
delete[] descandMax;
return maxProf;
}
};