知识点
贪心算法
解题思路
定义一个变量 maxProfit 来表示当前的最大利润,初始值为0。然后,我们遍历 prices 列表,从第二天开始,将每天的价格与前一天的价格进行比较:
- 如果当前价格大于前一天的价格,说明牛群的价格上涨,我们可以将这头牛出售,获得利润为当前价格减去前一天的价格,然后将利润累加到 maxProfit 上。
- 如果当前价格等于或小于前一天的价格,说明牛群的价格下跌或者持平,我们不进行交易。
最后返回maxProfit就是最终利润。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int max_profitv2 (int[] prices) {
// write code here
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
}



京公网安备 11010502036488号