首页 > 试题广场 >

买卖股票的最好时机(三)

[编程题]买卖股票的最好时机(三)
  • 热度指数:37568 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
假设你有一个数组prices,长度为n,其中prices[i]是某只股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1. 你最多可以对该股票有两笔交易操作,一笔交易代表着一次买入与一次卖出,但是再次购买前必须卖出之前的股票
2. 如果不能获取收益,请返回0
3. 假设买入卖出均无手续费

数据范围:,股票的价格满足
要求: 空间复杂度 ,时间复杂度
进阶:空间复杂度 ,时间复杂度
示例1

输入

[8,9,3,5,1,3]

输出

4

说明

第三天(股票价格=3)买进,第四天(股票价格=5)卖出,收益为2
第五天(股票价格=1)买进,第六天(股票价格=3)卖出,收益为2
总收益为4。              
示例2

输入

[9,8,4,1]

输出

0
示例3

输入

[1,2,8,3,8]

输出

12

说明

第一笔股票交易在第一天买进,第三天卖出;第二笔股票交易在第四天买进,第五天卖出;总收益为12。
因最多只可以同时持有一只股票,所以不能在第一天进行第一笔股票交易的买进操作,又在第二天进行第二笔股票交易的买进操作(此时第一笔股票交易还没卖出),最后两笔股票交易同时在第三天卖出,也即以上操作不满足题目要求。        

备注:
总天数不大于200000。保证股票每一天的价格在[1,100]范围内。

BM81的升级版

func maxProfit(prices []int) int {
    own1, los1, own2, los2 := -prices[0], 0, -prices[0], 0
    for i := 1; i < len(prices); i++ {
        own1, los1, own2, los2 = Max(own1, -prices[i]), Max(los1, own1+prices[i]), Max(own2, los1-prices[i]), Max(los2, own2+prices[i])
    }
    return los2
}
编辑于 2024-01-10 01:26:16 回复(0)
package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 两次交易所能获得的最大收益
 * @param prices int整型一维数组 股票每一天的价格
 * @return int整型
*/
func maxProfit( prices []int ) int {
    pre:=make([]int,4)
    pre[0]=-prices[0]
    pre[1]=-prices[0]
    pre[2]=0
    pre[3]=0
    ans:=0
    for i:=1;i<len(prices);i++{
        x:=max(max(pre[0]+prices[i],pre[1]+prices[i]),max(pre[2],pre[3]))
        if x>ans{
            ans=x
        }
        cur:=make([]int,4)
        cur[0]=max(pre[0],pre[3]-prices[i])
        cur[1]=max(pre[1],pre[2]-prices[i])
        cur[2]=max(pre[2],pre[0]+prices[i])
        cur[3]=pre[3]
        pre=cur
    }
    return ans
}

func max(a,b int)int{
    if a>b{
        return a
    }
    return b
}

发表于 2023-02-19 23:16:12 回复(0)
package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 两次交易所能获得的最大收益
 * @param prices int整型一维数组 股票每一天的价格
 * @return int整型
*/
func maxProfit( prices []int ) int {
    // write code here
    if len(prices) < 2 {
        return 0
    }
    var buy1, buy2, profit1, profit2 int
    buy1 = prices[0]
    buy2 = prices[0]
    profit1 = 0
    profit2 = 0
    for _, price := range(prices) {
        buy1 = min(buy1, price)
        profit1 = max(profit1, price - buy1)
        buy2 = min(buy2, price - profit1)
        profit2 = max(profit2, price - buy2)
    }
    return profit2
}
func max(num1, num2 int) int {
        if num1> num2 {
            return num1
        }
        return num2
}

func min(num1, num2 int) int {
        if num1> num2 {
            return num2
        }
        return num1
}


发表于 2021-08-03 22:12:21 回复(0)