leetcode-122. Best Time to Buy and Sell Stock II

原创 2016年08月30日 22:59:17

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).

题意解析:

题目就是告诉你有一个数组,index代表了日期,prices代表了价格,如{1,2,4,5,1},我们可以在1日买入,5日卖出,赚取4元,或者1日买入2日卖出,2日买入3日卖出,3日买入,4日卖出,赚取的同样是4元。不过,1日买入,2日买入这样的行为是不被允许的。

这题其实很简单,看了我上面的题意解析其实就不难发现,两种情况结果竟然是一样的,其实我们没有必要跨日期比较,我们只需要两天两天比较就行了,只要日期是增序的,那么肯定就是赚钱的。当天买第二天卖就行。最后总和就是总收益,代码如下:

public class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        for(int i = 1; i < prices.length; i++){
            if(prices[i] > prices[i - 1]){
                result += prices[i] - prices[i - 1];
            }
        }
        return result;
    }
}
复杂度O(n),简单,快速。应该就是最优算法了。

大家速度也差不多,看来这道题应该只是easy的

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

Leetcode 122 . Best Time to Buy and Sell Stock II

问题描述 Say you have an array for which the ith element is the price of a given stock on day i. Desig...

LeetCode 122 -- Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

【LeetCode-122】Best Time to Buy and Sell Stock II

时间复杂度是O(n),直接上代码吧,代码注释都写好了,哇咔咔 public class BestTimetoBuyandSellStockII { public static int maxP...

Leetcode 122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.Design an alg...

[leetcode] 122. Best Time to Buy and Sell Stock II

题目: Say you have an array for which the ith element is the price of a given stock on day i.Design a...

[Leetcode]122. Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock IISay you have an array for which the i-th element is the price...

[leetcode]: 122. Best Time to Buy and Sell Stock II

1.题目描述Say you have an array for which the ith element is the price of a given stock on day i. Desig...

LeetCode 122. Best Time to Buy and Sell Stock II

       大概题意:给定一个数组,数组的元素i表示第i天石头买入或者卖出的价格,求出能够赚到最多的钱的数目。注意不能在同一天买入和卖出。不限制买入卖出的次数。注意只有卖掉原来买入的石头之后才...

122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.Design an alg...

Best Time to Buy and Sell Stock II(leetcode)

题目: Say you have an array for which the ith element is the price of a given stock on day i. ...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)