zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】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).

    解题:

    将数组中每一个值都想象成数轴上的一个点,只要当前点比前一个点上升了,则此段收益就能够通过买入卖出获得;(即使是连续上升,可以中间段不卖出,收益也全都获得,因此不影响计算策略)。

    代码:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         int size = prices.size();
     5         int maxP = 0;
     6         for (int i = 1; i < size; ++i) {
     7             if (prices[i] > prices[i-1])
     8                 maxP += prices[i] - prices[i-1];
     9         }
    10         return maxP;
    11     }
    12 };
  • 相关阅读:
    Codis的源码编译生成tar包
    Jenkins安装war版本
    Eclipse中src/main/resources配置文件启动问题
    关于Web项目的pom文件处理
    spark streaming的理解和应用
    Azkaban安装
    Mysql安装
    Oracle递归操作
    WebService 入门
    BaseAction 类
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4240446.html
Copyright © 2011-2022 走看看