标签:ret nlog for lang java 动态 时间复杂度 笔试题 nlogn
一、分治法
时间复杂度:O(NlogN)
通过70%样例,超时
import java.util.*;
public class Main {
static int res = 0;
static void solution(int[] a, int i, int j, int x) {
if(i > j || i < 0 || i >= a.length || j < 0 || j >= a.length) return;
int idx = i;
for(int k = i+1; k <= j; k++)
if(a[k] < a[idx]) idx = k;
res += (a[idx]-x);
solution(a, i, idx-1, a[idx]);
solution(a, idx+1, j, a[idx]);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0; i < n; i++) {
a[i] = sc.nextInt();
}
solution(a, 0, n-1, 0);
System.out.println(res);
}
}
二、贪心
时间复杂度: O(N)
import java.util.*;
public class Main {
static int res = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0; i < n; i++) {
a[i] = sc.nextInt();
}
int res = a[n-1];
for(int i=1; i < n; i++) {
if(a[i-1] > a[i])
res += a[i-1] - a[i];
}
System.out.println(res);
}
}
三、动态规划
时间复杂度:O(N)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0; i < n; i++) {
a[i] = sc.nextInt();
}
int[] f = new int[n];
f[0] = a[0];
for(int i=1; i < n; i++) {
if(a[i] > a[i-1])
f[i] = f[i-1] + a[i] - a[i-1];
else
f[i] = f[i-1];
}
System.out.println(f[n-1]);
}
}
/*
f[i] 表示 完成前i个花园的种花计划最少要天数。
a[i] <= a[i-1], f[i] = f[i-1]
否则, f[i] = f[i-1] + (a[i] - a[i-1])
*/
标签:ret nlog for lang java 动态 时间复杂度 笔试题 nlogn
原文地址:https://www.cnblogs.com/lixyuan/p/13185357.html