LanQiaoTestCodes/最大化交易利润.java

38 lines
929 B
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package LanQiaoOJ;
import java.util.Scanner;
/*
* 实现一个算法寻找最大化股票交易利润的策略。介绍如下:
股票价格每天都在变化,以数组的索表示交易日,以数组的元素表示每天的股票价格。
可以通过买入和卖出获得利润。一天只能进行一次买入或卖出操作,一次买入加卖出操作称为一次交易次数。
你只能交易一次,求使得利润最大的交易策略。
输入描述
第一行为数字N,表示共有N天。
第二行为N个数字A,表示每天的股票价格。
其中1≤N,A≤104。**/
public class 最大化交易利润 {
public static void main(String[] args) {
// TODO Auto-generated method stub
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 ans=(int)-1e4;
//价格最低的时候
int min=(int)1e4;
//循环枚举出那天卖出
for(int i=0;i<n;i++) {
if(i>0)
ans=Math.max(ans, a[i]-min);
min=Math.min(min, a[i]);
}
System.out.print(ans);
}
}