贪心:每当下一天股票价格相对于今天是下降的,那么就将股票卖出,并在明天买入。需要注意:在最后一天一定需要将股票卖出,因为没有下一天了。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 计算最大收益
* @param prices int整型一维数组 股票每一天的价格
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int res = 0;
int left = 0;
int n = prices.length;
for(int i = 0;i < n;i++) {
if(i + 1 < n && prices[i] > prices[i+1]) {
res += prices[i] - prices[left];
left = i + 1;
}
if(i + 1 == n) {
res += prices[i] - prices[left];
}
}
return res;
}
}