算法分析
初始化:f[0][2] = f[0][1] = 0
,f[0][0] = -INF
, 因为在第0
个股票一定是无货的,必定从这个位置开始转移才有效
时间复杂度 $O(n)$
参考文献
算法提高课
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 100010, INF = 0x3f3f3f3f;
static int n;
static int[] w = new int[N];
static int[][] f = new int[N][3];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
String[] s1 = br.readLine().split(" ");
for(int i = 1;i <= n;i ++) w[i] = Integer.parseInt(s1[i - 1]);
f[0][2] = f[0][1] = 0; f[0][0] = -INF;
for(int i = 1;i <= n;i ++)
{
f[i][0] = Math.max(f[i - 1][0], f[i - 1][2] - w[i]);
f[i][1] = f[i - 1][0] + w[i];
f[i][2] = Math.max(f[i - 1][1], f[i - 1][2]);
}
System.out.println(Math.max(f[n][1], f[n][2]));
}
}