zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock II

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    解析:

    贪心法,低进高出,把所有正的价格差价相加起来。
    把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 数组长度

     1 class Solution
     2 {
     3 public:
     4     int maxProfit(vector<int> &prices)
     5     {
     6         int sum = 0;
     7         for (int i = 1; i < prices.size(); i++)
     8         {
     9             int diff = prices[i] - prices[i - 1];
    10             if (diff > 0) sum += diff;
    11         }
    12         return sum;
    13     }
    14 };

    这题相处了低进高出了,但是想麻烦的,总想着先求出出拐点,再计算拐点之间的差

  • 相关阅读:
    View相关知识学习总结
    关于Android四大组件的学习总结
    Android开发框架--AndroidAnnotations(一)
    USACO 3.4
    hdu 2723
    hdu 2721
    hdu 2719
    hdu 1527
    hdu 1260
    hdu 2603
  • 原文地址:https://www.cnblogs.com/raichen/p/4932961.html
Copyright © 2011-2022 走看看