代码随想录算法训练营第三十二天| 122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II
122.买卖股票的最佳时机II
题目链接 文章讲解
class Solution {
public :
int maxProfit ( vector< int > & prices) {
int ans = 0 ;
for ( int i = 1 ; i < prices. size ( ) ; i++ ) {
ans += max ( prices[ i] - prices[ i - 1 ] , 0 ) ;
}
return ans;
}
} ;
55. 跳跃游戏
题目链接 文章讲解
class Solution {
public :
bool canJump ( vector< int > & nums) {
int cover = 0 ;
for ( int i = 0 ; i <= cover && i < nums. size ( ) ; i++ ) {
cover = max ( cover, i + nums[ i] ) ;
}
return cover >= nums. size ( ) - 1 ;
}
} ;
45.跳跃游戏II
题目链接 文章讲解
class Solution {
public :
int jump ( vector< int > & nums) {
if ( nums. size ( ) == 1 ) return 0 ;
int ans = 0 ;
int curCover = 0 ;
int nextCover = 0 ;
for ( int i = 0 ; i < nums. size ( ) ; i++ ) {
nextCover = max ( nextCover, i + nums[ i] ) ;
if ( i == curCover) {
ans++ ;
curCover = nextCover;
if ( nextCover >= nums. size ( ) - 1 ) break ;
}
}
return ans;
}
} ;