[LeetCode] Best Time to Buy and Sell Stock II
2014-04-30 10:10
381 查看
Total Accepted: 12408 Total
Submissions: 34893
ay 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).
public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if (len <= 1) return 0;
int sum = 0;
for (int i = 1; i < len; i++) {
if (prices[i] > prices[i-1]) sum += prices[i] - prices[i-1];
}
return sum;
}
}
Submissions: 34893
ay 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).
public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if (len <= 1) return 0;
int sum = 0;
for (int i = 1; i < len; i++) {
if (prices[i] > prices[i-1]) sum += prices[i] - prices[i-1];
}
return sum;
}
}
相关文章推荐
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- javascript数组操作总结和属性、方法介绍
- mysql_fetch_assoc和mysql_fetch_row的功能加起来就是mysql_fetch_array
- JavaScript Array扩展实现代码
- C#中Array与ArrayList用法及转换的方法
- Array栈方法和队列方法的特点说明
- Array.prototype.slice 使用扩展
- Array, Array Constructor, for in loop, typeof, instanceOf
- 实例详解ECMAScript5中新增的Array方法
- js Array的用法总结
- JavaScript 判断判断某个对象是Object还是一个Array
- Javascript中的Array数组对象详谈
- js模拟实现Array的sort方法
- 在javascript将NodeList作为Array数组处理的方法
- PHP array_multisort()函数的使用札记
- PHP中array_merge和array相加的区别分析
- Sorting Array Values in PHP(数组排序)
- 深入array multisort排序原理的详解
- Array 重排序方法和操作方法的简单实例
- js中array的sort()方法使用介绍