LeetCode - Best Time to Buy and Sell Stock II
2014-01-13 15:27
357 查看
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).
http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Solution:
Pretty simple, just need to find all ascending section. Or try to find all prices[i] that prices[i] > prices[i-1].
https://github.com/starcroce/leetcode/blob/master/best_time_to_buy_and_sell_stock_II.cpp
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).
http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Solution:
Pretty simple, just need to find all ascending section. Or try to find all prices[i] that prices[i] > prices[i-1].
https://github.com/starcroce/leetcode/blob/master/best_time_to_buy_and_sell_stock_II.cpp
// 52 ms for 198 test cases class Solution { public: int maxProfit(vector<int> &prices) { // Note: The Solution object is instantiated only once and is reused by each test case. int profit = 0; for(int i = 1; i < prices.size();i++){ int diff = prices[i] - prices[i-1]; if(diff > 0) { profit += diff; } } return profit; } };
相关文章推荐
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- mysql_fetch_assoc和mysql_fetch_row的功能加起来就是mysql_fetch_array
- JavaScript Array扩展实现代码
- C#中Array与ArrayList用法及转换的方法
- Array.prototype.slice 使用扩展
- Array, Array Constructor, for in loop, typeof, instanceOf
- 实例详解ECMAScript5中新增的Array方法
- js Array的用法总结
- JavaScript 判断判断某个对象是Object还是一个Array
- js模拟实现Array的sort方法
- 在javascript将NodeList作为Array数组处理的方法
- PHP array_multisort()函数的使用札记
- PHP中array_merge和array相加的区别分析
- Sorting Array Values in PHP(数组排序)
- 深入array multisort排序原理的详解
- php下关于Cannot use a scalar value as an array的解决办法
- Array.prototype.concat不是通用方法反驳[译]
- Array.prototype 的泛型应用分析
- PHP array操作10个小技巧分享
- JavaScript高级程序设计 读书笔记之九 本地对象Array