150. Best Time to Buy and Sell Stock II【medium】
2024-08-26 23:27:51
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example
Given an example [2,1,2,0,1], return 2
解法一:
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
int total = ;
if (!prices.empty()) {
for (int i = ; i < prices.size() - ; i++) {
if (prices[i + ] > prices[i]) {
total += (prices[i + ] - prices[i]);
}
}
}
return total;
}
};
greedy的思想,只要是有收益就加上。
参考@NineChapter 的代码
解法二:
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 0; i < prices.length - 1; i++) {
int diff = prices[i + 1] - prices[i];
if (diff > 0) {
profit += diff;
}
}
return profit;
}
}
和解法一思路一样,看起来更舒服一些的代码风格。
参考@NineChapter 的代码
最新文章
- java 运算符使表达式结果类型自动提升
- 重新初始化 VS2010
- SSH的各个配置文件:
- mysql 的2个关于事务和安全性的参数
- sina sae 部署 java ssh 项目
- hdu 3874 Necklace(bit树+事先对查询区间右端点排序)
- TD8.0迁移到QC9.2,自动迁移失败,手动迁移
- JAVA面试题和答案
- 【NOIP模拟】board(线段树维护二进制,树序号化为二进制)
- java虚拟机工具入门
- Nginx常用模块安装命令
- mac 下SonarQube 安装与使用
- XV Open Cup named after E.V. Pankratiev. GP of Siberia-Swimming
- asp.net项目配置Web.config,支持JSON
- jQuery文档处理总结
- mysql 事务队列 写入 幂等性 重复写入
- springboot配置hibernate jpa多数据源
- JavaScript计算指定日期与当前日期的相差天数
- Python——杂记
- SqlServr性能优化性能之层次结构(十五)