题目描述
股票系列!这次加入了冷冻期要素,需要考虑更多的状态
思路 && 代码
每天,都有三个状态:开一个 dp = int[n][3] 二维数组 主要思路…就是理解几种状态,以及转移的思路(见注释) 时空复杂度:O(n)、O(n)
class Solution { public int maxProfit ( int [ ] prices) { int [ ] [ ] dp = new int [ prices. length] [ 3 ] ; dp[ 0 ] [ 0 ] = - prices[ 0 ] ; dp[ 0 ] [ 1 ] = 0 ; dp[ 0 ] [ 2 ] = 0 ; for ( int i = 1 ; i < prices. length; ++ i) { dp[ i] [ 0 ] = Math . max ( dp[ i - 1 ] [ 0 ] , dp[ i - 1 ] [ 1 ] - prices[ i] ) ; dp[ i] [ 1 ] = Math . max ( dp[ i - 1 ] [ 1 ] , dp[ i - 1 ] [ 2 ] ) ; dp[ i] [ 2 ] = dp[ i - 1 ] [ 0 ] + prices[ i] ; } return Math . max ( dp[ prices. length - 1 ] [ 1 ] , dp[ prices. length - 1 ] [ 2 ] ) ; }
}
class Solution { public int maxProfit ( int [ ] prices) { int [ ] [ ] dp = new int [ prices. length] [ 3 ] ; dp[ 0 ] [ 0 ] = - prices[ 0 ] ; dp[ 0 ] [ 1 ] = 0 ; dp[ 0 ] [ 2 ] = 0 ; for ( int i = 1 ; i < prices. length; ++ i) { dp[ i] [ 0 ] = Math . max ( dp[ i - 1 ] [ 0 ] , dp[ i - 1 ] [ 1 ] - prices[ i] ) ; dp[ i] [ 1 ] = Math . max ( dp[ i - 1 ] [ 1 ] , dp[ i - 1 ] [ 2 ] ) ; dp[ i] [ 2 ] = dp[ i - 1 ] [ 0 ] + prices[ i] ; } return Math . max ( dp[ prices. length - 1 ] [ 1 ] , dp[ prices. length - 1 ] [ 2 ] ) ; }
}
二刷
代码量少的一,就 9 行!但是难度还是有。 我觉得难点在于状态的考虑,但是理清状态之后,或许就很难做错了= =
class Solution { public int maxProfit ( int [ ] prices) { int [ ] [ ] dp = new int [ prices. length] [ 3 ] ; dp[ 0 ] [ 0 ] = - prices[ 0 ] ; dp[ 0 ] [ 1 ] = 0 ; dp[ 0 ] [ 2 ] = 0 ; for ( int i = 1 ; i < prices. length; i++ ) { dp[ i] [ 0 ] = Math . max ( dp[ i - 1 ] [ 1 ] - prices[ i] , dp[ i - 1 ] [ 0 ] ) ; dp[ i] [ 1 ] = Math . max ( dp[ i - 1 ] [ 1 ] , dp[ i - 1 ] [ 2 ] ) ; dp[ i] [ 2 ] = dp[ i - 1 ] [ 0 ] + prices[ i] ; } return Math . max ( dp[ prices. length - 1 ] [ 1 ] , dp[ prices. length - 1 ] [ 2 ] ) ; }
}