[关闭]
@XQF 2018-03-07T22:57:25.000000Z 字数 1020 阅读 817

如何求数对之差的最大值?

数据结构与算法


题目描述,数组中的一个数字减去右边子数组中的一个数字可以得到一个差值,所所得可能差值中的最大值

1.首发----我的dp

保留前面子数组中的最大值就可以了

  1. public class Solution {
  2. public int getMax(int[] nums) {
  3. if (nums == null || nums.length == 0) {
  4. return -1;
  5. }
  6. int[] dp = new int[nums.length];
  7. dp[0] = nums[0];
  8. int max = 0;
  9. int temp;
  10. for (int i = 1; i < nums.length; i++) {
  11. dp[i] = Math.max(dp[i - 1], nums[i]);
  12. if (dp[i] != nums[i]) {
  13. temp = dp[i] - nums[i];
  14. if (temp > max) {
  15. max = temp;
  16. }
  17. }
  18. }
  19. System.out.println("result :" + max);
  20. return max;
  21. }
  22. public static void main(String[] args) {
  23. Solution solution = new Solution();
  24. int[] nums = {1, 2, 10, 4, 100, 5, 6, 6};
  25. solution.getMax(nums);
  26. }
  27. }

2.空间优化的动态规划

dp[i]和dp[i-1]是两个不同的状态,可以不保留,用同一变量的不同位置来表示不同的状态

  1. public class Solution {
  2. public int getMax(int[] nums) {
  3. if (nums == null || nums.length == 0) {
  4. return -1;
  5. }
  6. int dp = nums[0];
  7. int max = 0;
  8. int temp;
  9. for (int i = 1; i < nums.length; i++) {
  10. dp = Math.max(dp, nums[i]);
  11. if (dp != nums[i]) {
  12. temp = dp - nums[i];
  13. if (temp > max) {
  14. max = temp;
  15. }
  16. }
  17. }
  18. System.out.println("result :" + max);
  19. return max;
  20. }
  21. public static void main(String[] args) {
  22. Solution solution = new Solution();
  23. int[] nums = {1, 2, 10, 4, 100, 5, 6, 6};
  24. solution.getMax(nums);
  25. }
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注