剑指offer面试题63(java版):股票的最大利润
思路
从头开始遍历, 记录遍历过程中的最小值, 同时计算并更新arr[i] - min的最大值 感觉很简单, 其实还是要巩固自己的思路, 比如明确每次for循环在做什么: 计算卖出价为arr[i]时能够获得的最大利润
class Solution {
public int maxProfit ( int [ ] prices) {
int n = prices. length;
if ( n== 0 ) {
return 0 ;
}
int [ ] [ ] dp = new int [ n] [ 2 ] ;
dp[ 0 ] [ 1 ] = - prices[ 0 ] ;
for ( int i= 1 ; i< n; 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 ] , - prices[ i] ) ;
}
return dp[ n- 1 ] [ 0 ] ;
}
}
class Solution {
public int maxProfit ( int [ ] prices) {
int n = prices. length;
if ( n== 0 ) {
return 0 ;
}
int s0 = 0 ;
int s1 = - prices[ 0 ] ;
int s2 = 0 ;
for ( int i= 0 ; i< n; i++ ) {
s0 = 0 ;
s1 = Math. max ( s1, - prices[ i] ) ;
s2 = Math. max ( s2, s1 + prices[ i] ) ;
}
return s2;
}
}
public int MaxDiff ( int [ ] arr) {
if ( arr. length< 1 ) return - 1 ;
int min = arr[ 0 ] ;
int delta = arr[ 1 ] - min;
for ( int i= 1 ; i< arr. length; i++ ) {
if ( arr[ i- 1 ] < min)
min = arr[ i- 1 ] ;
if ( arr[ i] - min > delta)
delta = arr[ i] - min;
}
return delta;
}