Leetcode_122_Best Time to Buy and Sell Stock II
来源:互联网 发布:阿里云机顶盒安装软件 编辑:程序博客网 时间:2024/06/15 01:03
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43155725
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).
思路:
(1)题意为给定一个数组,数组中第i个元素的值对应着第i天的股票,你可以完成多次交易,但是每次交易只能买入一次并卖出,求进行多次交易所能得到的最大利润。该题为Best Time to Buy and Sell Stock的加强版。
(2)与Best Time to Buy and Sell Stock类似,该题同样考查的是最大差值。只不过该题考查数组中所有相邻且递增元素的数值之差的总和。只要第i+1天的值大于第i天的值,则可买入,求得利润(差值),遍历整个数组,得到所用差值之和即为总的利润。
(3)该题还是比较简单。希望对你有所帮助。
算法代码实现如下:
/** * * @author liqq */public int maxProfit(int[] x) {if (x == null || x.length <= 1)return 0;int min = x[0];int profit = 0;for (int i = 0; i < x.length; i++) {if (min > x[i]) {min = x[i];} else {profit += x[i] - min;min = x[i];}}return profit;}
- Leetcode_122_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
- Producer Example
- 提高 Linux 上 socket 性能
- arm-linux-gcc裸机程序开发(三)
- OC学习笔记一---第一个OC程序
- Java网络编程问题
- Leetcode_122_Best Time to Buy and Sell Stock II
- Android 在Ubuntu12.04上配置两个JDK
- Servlet 3.0 新特性详解
- 网络编程字节序问题
- 亲爱的用户 欢迎来到jcb00s~
- BZOJ 2458 BeiJing2011 最小三角形 计算几何+分治
- JAVA开发中的中文问题
- 谈谈代码走读
- Android注解支持(Support Annotations)