[LeetCode9]Best Time to Buy and Sell Stock II
来源:互联网 发布:python编辑器 sub 编辑:程序博客网 时间:2024/06/07 18:12
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).
Analysis:
A bit different with previous one. Since we can make unlimited transactions, this question turns to sum all the positive price difference.
So, scan from left to right, and add all positive diff value.
Java
public int maxProfit(int[] prices) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int maxPro = 0; for(int i =1; i<prices.length;i++){ int delta = prices[i] - prices[i-1]; if(delta > 0) maxPro += delta; } return maxPro; }
c++
int maxProfit(vector<int> &prices) { int sum = 0; for(int i=1;i<prices.size();i++){ if(prices[i]-prices[i-1] > 0) sum+= prices[i]-prices[i-1]; } return sum; }
0 0
- [LeetCode9]Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- 第一篇文章
- Libsvm各主要函数参数详解
- [数据库]树结构的数据库设计
- 电商实训四:网络营销方案设计及实施
- cocos2d-x 3.0 引用第三方库 及编译成apk时android mk文件写法
- [LeetCode9]Best Time to Buy and Sell Stock II
- UI中图片的完美放大
- centos6.5搭建apache+mysql+php环境
- ffmpeg(10) mpegts_read_header part 2
- httpd-2.4.x 版本客户端访问控制
- pythoner
- 字符串元素重排高效算法集合
- android异常处理概述
- 百度之星2010复赛第二场第三题《蜗牛》