具体代码如下
package com.trs.codetool.core; import java.util.Scanner; /** * @author zheng.changgang * @date 2019-12-19 10:01 * 这一周股市价格为[2,6,1,4,8],求哪一天买入哪一天卖出,可获得最大收益,最大收益为多少 */ public class GuShiTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); int[] nums = new int[num]; for(int i=0;i<num;i++) { nums[i] = scanner.nextInt(); } // 得到最大收益 getBestGuShi(nums); } private static void getBestGuShi(int[] nums) { int profit = 0; int min = nums[0]; int buyDay = 0; int sellDay = 0; for(int i=1;i<nums.length;i++) { if(nums[i] < min) { min = nums[i]; buyDay = i; } else if(nums[i] - min > profit) { profit = nums[i] - min; sellDay = i; } } System.out.println((buyDay+1) + "天买入==="+ (sellDay +1) + "天卖出==="+"可获最大收益=="+profit); } }
运行结果如下: