题解 | #牛群买卖策略优化#
牛群买卖策略优化
https://www.nowcoder.com/practice/c8514318443a48218efde630ae11b4c3
考察的知识点:贪心;
解答方法分析:
- 定义一个变量 profit 来表示当前的利润,初始化为 0。
- 从列表的第二个元素开始遍历,假设当前遍历到的元素索引为 i。
- 如果当前价格 prices[i] 大于前一天的价格 prices[i-1],说明可以进行交易。此时将利润增加 prices[i] - prices[i-1]。
- 最后返回最终的利润 profit。
所用编程语言:C++;
完整编程代码:↓
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型vector
* @return int整型
*/
int max_profitv2(vector<int>& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
};
查看15道真题和解析