买卖股票的最佳时机
力扣简单习题1:
力扣简单习题2:
大致思路
两题的区别是,第一题只进行一次交易,第二题可以多次交易
第一题:遍历时随时计算最小值和最大值,找到他们的差值即可。
第二题:遍历时记录比前一个数大的值,碰到此值时,进行累加即可。
代码实现
第一题:
package com.immunize.leetcode.besttimetosalestocks;
/**
* LeetCode习题:买卖股票的最佳时机
*
* 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
*
* 设计一个算法来计算你所能获取的最大利润。你只可以完成一笔交易。
*
* 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
*
* @author Mr IMMUNIZE
*
*/
public class BestTime01 {
// 原型方法
public int maxProfit(int[] prices) {
if (prices.length == 0)
return 0;
int max = 0;
int min = prices[0];
// 一次遍历即可实现,在遍历时记录最小值,并依次计算最大值即可。
for (int i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i] - min);
}
return max;
}
}
-----------------------------------------------------------------
package com.immunize.leetcode.besttimetosalestocks;
import java.util.Scanner;
/**
* 买卖股票的最好时机1:测试数据:[7,1,5,3,6,4] [1,2,3,4,5] [7,6,4,3,1]
*
* @author Mr IMMUNIZE
*
*/
public class BestTime01Test {
public static void main(String[] args) {
BestTime01 bt1 = new BestTime01();
System.out.println("请输入数组:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
// String[] c = s.split("\\s+");
String[] c = s.split(",");
int[] prices = new int[c.length];
for (int i = 0; i < c.length; i++) {
prices[i] = Integer.parseInt(c[i]);
}
System.out.println("最大利润为:" + bt1.maxProfit(prices));
}
}
第二题:
package com.immunize.leetcode.besttimetosalestocks;
/**
* LeetCode习题:买卖股票的最佳时机
*
* 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
*
* 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
*
* 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
*
* @author Mr IMMUNIZE
*
*/
public class BestTime02 {
// 原型方法
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 0; i < prices.length - 1; i++) {
int c = prices[i + 1] - prices[i];
if (c > 0) {
profit = profit + c;
}
}
return profit;
}
}
---------------------------------------------------------------------------
package com.immunize.leetcode.besttimetosalestocks;
import java.util.Scanner;
/**
* 买卖股票的最好时机2:测试数据:[7,1,5,3,6,4] [1,2,3,4,5] [7,6,4,3,1]
*
* @author Mr IMMUNIZE
*
*/
public class BestTime02Test {
public static void main(String[] args) {
BestTime02 bt2 = new BestTime02();
System.out.println("请输入数组:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
// String[] c = s.split("\\s+");
String[] c = s.split(",");
int[] prices = new int[c.length];
for (int i = 0; i < c.length; i++) {
prices[i] = Integer.parseInt(c[i]);
}
System.out.println("最大利润为:" + bt2.maxProfit(prices));
}
}