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 的代码

最新文章

  1. java 运算符使表达式结果类型自动提升
  2. 重新初始化 VS2010
  3. SSH的各个配置文件:
  4. mysql 的2个关于事务和安全性的参数
  5. sina sae 部署 java ssh 项目
  6. hdu 3874 Necklace(bit树+事先对查询区间右端点排序)
  7. TD8.0迁移到QC9.2,自动迁移失败,手动迁移
  8. JAVA面试题和答案
  9. 【NOIP模拟】board(线段树维护二进制,树序号化为二进制)
  10. java虚拟机工具入门
  11. Nginx常用模块安装命令
  12. mac 下SonarQube 安装与使用
  13. XV Open Cup named after E.V. Pankratiev. GP of Siberia-Swimming
  14. asp.net项目配置Web.config,支持JSON
  15. jQuery文档处理总结
  16. mysql 事务队列 写入 幂等性 重复写入
  17. springboot配置hibernate jpa多数据源
  18. JavaScript计算指定日期与当前日期的相差天数
  19. Python——杂记
  20. SqlServr性能优化性能之层次结构(十五)

热门文章

  1. ORACLE常用性能监控SQL【一】
  2. AS3.0纯代码编写的两款loading效果
  3. 区块链核心技术:拜占庭共识算法之PBFT
  4. Openshift初步学习问题集
  5. PostgreSQL配置文件--QUERY TUNING
  6. 前端对比插件JS
  7. synchronized 线程同步-类级别锁定
  8. 绕过WAF继续SQL注入
  9. excel宏调用webservice使用存储过程同步excel数据的方法
  10. Boost.Asio c++ 网络编程翻译(21)