//本题用动态规划求解 /dp[n][2] 中两列0,1分别表示持有股票和未持有股票 n代表当天最大收益 初始值dp[0][0] = 0; //dp状态转移方程为 dp[n][0] = max(dp[n-1][0],dp[n-1][1]+prices[n]) 当天最大收益由两种情况递推而来 //1.前面的日子仍未购买 2.之前购买,现在卖出 //dp[n][1] = max(dp[n-1][1],-prices[n]) //1.之前买了,现在也不卖 2.之前没买 现在买了 #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); std::cin.tie(nullptr); int length = 0; cin>>length; int inits[length]; int temp = 0; for (int i = 0; i < length; ++i) { cin>>temp; inits[i] = temp; } int dp[length][2]; dp[0][0] = 0; dp[0][1] = -inits[0]; for (int i = 1; i < length; ++i) { dp[i][0] = max(dp[i-1][0],dp[i-1][1] + inits[i]); dp[i][1] = max(dp[i-1][1],-inits[i]); } cout<<dp[length-1][0]; } // 64 位输出请用 printf("%lld")
import java.io.*; import java.lang.reflect.Array; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main {public static void main(String[] args) throws Exception { StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(System.out)); int length = 0; streamTokenizer.nextToken(); length = (int) streamTokenizer.nval;i nt[] ints = new int[length]; for (int i = 0; i < length; i++) { streamTokenizer.nextToken(); ints[i] = (int) streamTokenizer.nval; } int[][] dp = new int[length][2]; dp[0][0] = 0; dp[0][1] = -ints[0]; for (int i = 1; i < length; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + ints[i]); dp[i][1] = Math.max(dp[i - 1][1], - ints[i]); } printWriter.println(dp[length - 1][0]); printWriter.flush(); }
}