• 股票的最大利润


    题目:

    假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖股票一次可能获得的最大利润是多少?

    例如:一只股票在某些时间节点的价格是{9,11,8,5,7,12,16,14}。

    如果我们能在价格为5的时候买入并在价格16的时卖出,则能获得最大的利润。

    思路:

    我们定义函数diff(i)为当卖出价格为数组中第i个数字时可能获得的最大利润。显然,在卖出价格固定时,买入价越低获得的利润最大。也就是说,如果扫描到数组中第i个数字时,只要我们能够记住之前i-1个数字中的最小值,就能算出当前价位卖出时,可能获得的最大利润。

     1 public class Solution {
     2 
     3     public int maxDiff(int[] numbers) {
     4         if(numbers == null && numbers.length) {
     5             return 0;
     6         }
     7 
     8         int min = numbers[0];
     9         int maxDiff = numbers[1]-numbers[0];
    10 
    11         for(int i = 2; i < numbers.length; i++) {
    12             
    13             // you should know here numbers[i-1]
    14             if(numbers[i-1] < min) {
    15                 min = numbers[i-1];
    16             }
    17 
    18             int currentDiff = numbers[i] - min;
    19 
    20             if(currentDiff > maxDiff) {
    21                 maxDiff = currentDiff;
    22             }
    23         }
    24 
    25         return maxDiff;
    26     }
    27 
    28 
    29     public static void main(String[] args) {
    30         Solution s = new Solution();
    31         int[] data = {9,11,8,5,7,12,16,14};
    32 
    33         System.out.println(s.maxDiff(data));
    34     }
    35 }
  • 相关阅读:
    hdu-5492 Find a path(dp)
    hdu-5493 Queue(二分+树状数组)
    bzoj-2243 2243: [SDOI2011]染色(树链剖分)
    codeforces 724
    codeforces 422A A. Borya and Hanabi(暴力)
    codeforces 442C C. Artem and Array(贪心)
    codeforces 442B B. Andrey and Problem(贪心)
    hdu-5918 Sequence I(kmp)
    poj-3739. Special Squares(二维前缀和)
    hdu-5927 Auxiliary Set(树形dp)
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10342270.html
Copyright © 2020-2023  润新知