how are you
1. Goal
Without considering the overall optimality, the algorithm obtains a local optimal solution in a certain sense .
2. Method
1. Divide the solved problem into several sub-problems
2. Solve each sub-problem to obtain the local optimal solution
of the sub-problem 3. Combine the local optimal solution of the sub-problem into a solution of the original problem
3. Examples
122. The Best Time to Buy and Sell Stocks II
class Solution {
public:
int maxProfit(vector<int>& prices) {
int answer = 0;
if(prices.size() < 2) return 0;
//每次都找当下可以赚钱的
for(int i = 0;i < prices.size() - 1;i++){
int diff = prices[i+1] - prices[i];
if(diff > 0) answer += diff;
}
return answer;
}
};