Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告

1 解题思想

首先请看下第一个问题:
Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告
题目给定的数组还是一样的含义,依旧代表股票的价格,但是现在不同的是,现在你可以任意次数的买卖(当然还是要先买后卖才行,不能买两次再卖等)

这道题目我的解法很naive,在第i天,只要第i+1天的售价高于第i天,那么我就买,然后i+1天卖了。

关于其中原理,可以认为是,我们这样做,赶上了所有可以赚钱的机会,且没有误入一个赔钱的机会。

可以理解为我们求得了(类似倒数)的每天利润差,我们赶上了所有增长的地方,所以肯定是最大的

2 原题

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

Subscribe to see which companies asked this question

3 AC解

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]>0)
                result+=(prices[i]-prices[i-1]);
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值