《leetCode》:Best Time to Buy and Sell Stock II
来源:互联网 发布:分答和知乎 编辑:程序博客网 时间:2024/06/16 17:05
题目
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).
思路
贪婪算法 :判断相邻的两个元素之差是否是大于零,如果大于零,则可以构成一次交易;
如果相邻的两个元素之差小于零,则可以理解为当天买当天卖,利润为零。综上所述:统计所有相邻的元素大于零的之和即为最大收益
实现代码如下:
int maxProfit(int* prices, int pricesSize) { if(prices==NULL||pricesSize<1){ return 0; } int profit=0; for(int i=1;i<pricesSize;i++){ profit+=(prices[i]-prices[i-1])>0?(prices[i]-prices[i-1]):0; } return profit; }
1 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [Leetcode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- LeetCode-Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- 创客工具汇总及介绍
- 写个函数用来对二维数组排序(新浪)
- 1028. List Sorting (25)
- 尺度不变特征变换(SIFT)算法介绍
- 数据库中join和left join的区别
- 《leetCode》:Best Time to Buy and Sell Stock II
- [CodeVS2822]爱在心中 做题笔记
- ViewPager 详解(一)---基本入门
- Python计算机视觉:第九章 图像分割
- [iOS]Objective-C Method Swizzling
- C++中的RVO和NRVO
- 写 5个不同的自己的函数来获取一个全路径的文件的扩展名, 允许封装php 库中已有 的函数(新浪)
- NumPy 简单应用
- Python计算机视觉:第十章 OpenCV