前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:122. Best Time to Buy and Sell Stock II

LeetCode笔记:122. Best Time to Buy and Sell Stock II

作者头像
Cloudox
发布2021-11-23 14:20:04
1310
发布2021-11-23 14:20:04
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

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

大意:

说你有这么一个表示一只股票每日股价的数组。 设计一个算法寻找最大收益。你可以随便完成多少次交易(比如,多次买入卖出)。然而你不能一次进行多次交易(在再次买入前你必须卖出股票)。

思路:

这等于是把股票以后的走向告诉你,让你躺着赚钱,那最大收益当然是低价买进高价卖出了,只不过还是要按照时间顺序,而且每次也只能买一股。

我们遍历股价,遇到不断下降的趋势,我们就等到降到最低了再买,然后等他开始上涨涨到最高点的时候卖出,以此往复,每次的收益累计就是最大收益了。

代码(Java):

代码语言:javascript
复制
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 1) return 0;
        
        int last = prices[0];
        int result = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < last) last = prices[i];
            else if (prices[i] > last) {
                int big = prices[i];
                i ++;
                for (; i < prices.length; i++) {
                    if (prices[i] > big) big = prices[i];
                    else break;
                }
                result += big - last;
                if (i >= prices.length - 1) break;
                else last = prices[i];
            }
        }
        return result;
    }
}

他山之石:

代码语言:javascript
复制
public class Solution {
public int maxProfit(int[] prices) {
    int total = 0;
    for (int i=0; i< prices.length-1; i++) {
        if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];
    }
    
    return total;
}

其实代码不用我那么麻烦,归根结底还是主要第二天有上涨就买入卖出,相当于把我的一次大操作分解成一天天的小操作,专做短线,想想也是这个理。

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
  • 他山之石:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档