Best Time to Buy and Sell Stocks 1, 2

1. Buy and sell only once

<?php


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param prices int整型一维数组 
 * @return int整型
 */

function maxProfit( $prices )
{
    // write code here
  // write code here
        $len = count($prices);
        // 特殊判断
        if ($len < 2) {
            return 0;
        }
        
 
        // dp[i][0] 下标为 i 这天结束的时候,不持股,手上拥有的现金数
        // dp[i][1] 下标为 i 这天结束的时候,持股,手上拥有的现金数
 
        // 初始化:不持股显然为 0,持股就需要减去第 1 天(下标为 0)的股价
        $dp[0][0] = 0;
        $dp[0][1] = -$prices[0];
 
        // 从第 2 天开始遍历
        for ($i = 1; $i < $len; $i++) {
            $dp[$i][0] =max($dp[$i - 1][0], $dp[$i - 1][1] + $prices[$i]);
            $dp[$i][1] = max($dp[$i - 1][1], -$prices[$i]);
        }
        return $dp[$len - 1][0];
    
}

2. You can buy and sell any number of times

<?php


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 计算最大收益
 * @param prices int整型一维数组 股票每一天的价格
 * @return int整型
 */
function maxProfit( $prices )
{
    // write code here
    $maxPr = 0;
    for($i = 1;$i<count($prices);++$i){
        if($prices[$i]>$prices[$i-1]){
            $maxPr = $maxPr + $prices[$i]-$prices[$i-1];
        }
    }
    return $maxPr;
}

3. You can only buy and sell for two rounds

<?php


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 两次交易所能获得的最大收益
 * @param prices int整型一维数组 股票每一天的价格
 * @return int整型
 */
function maxProfit( $prices )
{
    // write code here
   // $a = array_filter($prices);
    //var_dump($a);die;
  
    if(count($prices) == 0 ){
        return 0;
    }
    
        //初始化
        $dp[0][1] = -$prices[0];
        $dp[0][3] = -$prices[0];
        for ($i = 1; $i < count($prices); $i++) {
            $dp[$i][0] = $dp[$i - 1][0];
            //其中dp[i][1]有两个操作1)第i天没有操作2)第i天买入股票,所以此时最大收益,应该为这两个操作比大小
            $dp[$i][1] = max($dp[$i - 1][1], $dp[$i - 1][0] - $prices[$i]);
            //其中dp[i][2]有两个操作1)第i天没有操作2)第i天卖出股票,所以此时最大收益,应该为这两个操作比大小
            $dp[$i][2] = max($dp[$i - 1][2], $dp[$i - 1][1] + $prices[$i]);
            //其中dp[i][3]有两个操作1)第i天没有操作2)第i天买入股票,所以此时最大收益,应该为这两个操作比大小
            $dp[$i][3] = max($dp[$i - 1][3], $dp[$i - 1][2] - $prices[$i]);
            //其中dp[i][4]有两个操作1)第i天没有操作2)第i天卖出股票,所以此时最大收益,应该为这两个操作比大小
            $dp[$i][4] = max($dp[$i - 1][4], $dp[$i - 1][3] + $prices[$i]);
        }
        return $dp[count($prices) - 1][4]??0;
}

Guess you like

Origin blog.csdn.net/qq_40192867/article/details/123181441