比较简单的动态规划。用一个变量保存最小值,另一个变量保存最大收益。
遍历数组:
1.当该数比最小值小时,将其赋给最小值。
2.将该数与最小值相减得到该数所能得到的最大收益,若该收益比最大收益大,将其赋给最大收益
最终即得最大收益。
class Solution {
public:
/**
*
* @param prices int整型vector
* @return int整型
*/
int maxProfit(vector<int>& prices) {
// write code here
int max = 0;
int min = 10000;
for(int i = 0;i < prices.size();i++){
if(prices.at(i)<min){
min = prices.at(i);
}
int diff = prices.at(i) - min;
if(diff > max){
max = diff;
}
}
return max;
}
}; 
京公网安备 11010502036488号