• 买卖股票的最佳时机 II


    给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

    设计一个算法来计算最大的利润。你可以尽可能地完成更多的交易(多次买卖股票)。然而你不能同时参与多个交易(你必须在再次购买前出售股票)。

     1 package com.company;
     2 
     3 import java.util.HashMap;
     4 
     5 public class Main {
     6 
     7     public static void main(String[] args) {
     8         // write your code here
     9         int[] nums = {1, 3, 1, 5, 1, 8};
    10         Solution solution = new Solution();
    11         System.out.println("maxProfit " + solution.maxProfit(nums));
    12     }
    13 
    14     static class Solution {
    15         public int maxProfit(int[] nums) {
    16             HashMap<Integer, Integer> map = new HashMap<>();
    17             if (nums.length <= 1) {
    18                 return 0;
    19             } else {
    20                 int i = 0, j = 1;
    21                 for (; j < nums.length; ) {
    22                     if (nums[j - 1] <= nums[j]) {
    23                         if (j + 1 < nums.length) {
    24                             j++;
    25                         } else {
    26                             map.put(i, j);
    27                             break;
    28                         }
    29                     } else {
    30                         map.put(i, j - 1);
    31                         i = j;
    32                         j = j + 1;
    33                     }
    34                 }
    35             }
    36             int count = 0;
    37             for (HashMap.Entry<Integer, Integer> entry : map.entrySet()) {
    38                 int tmp = nums[entry.getValue()] - nums[entry.getKey()];
    39                 count = count + tmp;
    40             }
    41             return count;
    42         }
    43     }
    44 }

           该问题其实可以理解为寻找数组中 有N个增长子序列的问题,目前小马是这么理解的,也依照这个去写代码。但目前时间效率不高。

  • 相关阅读:
    箭头函数和普通函数的区别是什么?
    前端如何优化网站性能?
    instanceof原理
    call、apply区别
    函数的节流和防抖
    关于this的指向性问题
    undefined 和null的区别?
    浅谈堆和栈的理解?
    关于vue中watch和computed
    简单说一下什么是回流和重绘
  • 原文地址:https://www.cnblogs.com/Onlyou/p/8888411.html
Copyright © 2020-2023  润新知